【问题标题】:How can I change the row and colum background-color on hover a table element?如何在悬停表格元素时更改行和列背景颜色?
【发布时间】:2020-09-15 00:29:21
【问题描述】:

最大的问题是更改列背景颜色,因为列不是 HTML 上的元素。

【问题讨论】:

标签: javascript html css


【解决方案1】:

我使用简单的 tr:hover 来更改行背景颜色和一些 javascript 代码来解决列颜色问题,从而解决了这个问题。

First Stage (CSS): // 在悬停时改变一行的背景颜色。

tr:hover{
 background: #414141;
}

第二阶段(JavaScript)://在悬停时从列更改背景颜色。

let items = document.querySelectorAll('td')
let rows = document.querySelectorAll('tr')

items.forEach(function(item){
    item.onmouseover = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style.background = '#393939'
            }
        })
    }
    item.onmouseout = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style.background = '#414141'
            }
        })
    }
})

该解决方案有效,但是当我更改样式属性时,它似乎失去了该元素的悬停属性。所以,我创建了一个字典来保存元素样式。

第三阶段(JavaScript)://在悬停时从列更改背景颜色。不丢失任何样式属性:

let items = document.querySelectorAll('td')
let rows = document.querySelectorAll('tr')
var aux = {}

items.forEach(function(item){
    item.onmouseover = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                aux[item.cellIndex] = row.children[item.cellIndex].style
                row.children[item.cellIndex].style.background = '#393939'
            }
        })
    }
    item.onmouseout = function(){
        rows.forEach(function(row){
            if (row.rowIndex != 0){
                row.children[item.cellIndex].style = aux[item.cellIndex]
            }
        })
    }
})

我不知道这是否是解决问题的最佳方法,但对我有用。告诉我你是否有其他方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 2012-01-23
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 2015-02-20
    相关资源
    最近更新 更多