如何实现HTML表格单元格悬停时所在行列交叉高亮的效果
实现表格交叉悬停效果方案
方案1:纯CSS实现(现代浏览器兼容,Chrome 105+、Firefox 121+版本均支持)
利用CSS :has 选择器匹配悬停单元格所属列,配合行悬停选择器实现效果,无需修改现有HTML、不需要额外JS代码:
.card-body table{ width:100%; /* 新增:合并单元格边框避免高亮间隙 */ border-collapse: collapse; } .blank-cell, th{ background: #000; color: #fff; /* 新增:避免表头被行/列高亮覆盖 */ position: relative; z-index: 1; } td { text-align: center; padding: 4px 8px; } th{ background: #000; color: #fff; } /* 行高亮:当前行所有非空白单元格加浅紫色 */ tr:hover td:not(.blank-cell) { background: #d9c2e9; color: #000; } /* 列高亮:当前列所有非空白单元格加浅紫色 */ table:has(td:nth-child(1):hover) td:nth-child(1), table:has(td:nth-child(2):hover) td:nth-child(2), table:has(td:nth-child(3):hover) td:nth-child(3), table:has(td:nth-child(4):hover) td:nth-child(4), table:has(td:nth-child(5):hover) td:nth-child(5), /* 你共有28列,按上面格式补充到nth-child(28)即可 */ table:has(td:nth-child(28):hover) td:nth-child(28) { background: #d9c2e9; color: #000; } /* 悬停单元格样式优先级最高,覆盖行/列高亮 */ td:hover { background: #530288 !important; color: #fff !important; }
如果不想手动补全28列的选择器,可使用下方全兼容JS方案。
方案2:JS实现(全浏览器兼容,自动适配行列数)
无需修改现有HTML结构,新增一段JS代码和对应CSS即可,自动适配56行28列的大表格,性能无压力:
新增JS代码
document.addEventListener('DOMContentLoaded', function() { const table = document.querySelector('table'); const allCells = table.querySelectorAll('td'); allCells.forEach(cell => { // 鼠标进入单元格触发高亮 cell.addEventListener('mouseover', function() { const colIndex = this.cellIndex; const currentRow = this.parentElement; // 高亮当前行 currentRow.querySelectorAll('td:not(.blank-cell)').forEach(td => { td.classList.add('highlight'); }); // 高亮当前列 table.querySelectorAll(`tr td:nth-child(${colIndex + 1}):not(.blank-cell)`).forEach(td => { td.classList.add('highlight'); }); // 特殊高亮当前悬停单元格 this.classList.add('active-hover'); }); // 鼠标离开清除所有高亮 cell.addEventListener('mouseout', function() { table.querySelectorAll('.highlight, .active-hover').forEach(el => { el.classList.remove('highlight', 'active-hover'); }); }); }); });
新增对应CSS样式
/* 行/列统一高亮样式 */ td.highlight { background: #d9c2e9; color: #000; } /* 悬停单元格样式,和你原有样式保持一致 */ td.active-hover { background: #530288; color: #fff; } /* 原有td:hover规则可以删除,已通过active-hover实现 */
你可以自行调整#d9c2e9的色值,匹配你想要的浅紫色高亮效果。
内容的提问来源于stack exchange,提问作者Twisted
相关产品推荐
相关产品推荐

