javascript - 如何在悬停表格元素时更改行和列背景颜色?
问题描述
最大的问题是更改列背景颜色,因为列不是 HTML 上的元素。
解决方案
我使用简单的 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]
}
})
}
})
我不知道这是否是解决问题的最佳方法,但对我有用。告诉我你是否有其他方法。
推荐阅读
- typescript - Typescript - 如何从哈希图中删除值?
- dictionary - python嵌套字典中的棘手行为
- php - 如何在 wordpress 中删除数据库中的主表而不丢失 wordpress 站点?
- c# - c# .Net Visual Studio 显示导致页面显示的执行路径
- python - TypeError:“int”和“list”的实例之间不支持“>”
- css - 如何调整mat-option的位置
- c# - 复杂对象的隐藏字段未传递给控制器
- string - PowerShell 匹配字符串中的模式
- knockout.js - 使用数据表分页的数据绑定在 knockout.js 中不起作用
- java - 如何在 Java 项目中管理证书、信任库和密钥库密钥文件