首页 > 解决方案 > 如何在悬停表格元素时更改行和列背景颜色?

问题描述

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

标签: javascripthtmlcss

解决方案


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

第一阶段(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]
            }
        })
    }
})

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


推荐阅读