如何使用CSS为表格整列添加鼠标悬停背景色与过渡效果?
表格整列添加鼠标悬停背景色与过渡效果的实现方案
一、纯CSS实现(现代浏览器)
利用CSS的:has()选择器可以快速实现整列悬停效果,搭配过渡动画让颜色变化更平滑:
HTML 结构
<table> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>职业</th> </tr> </thead> <tbody> <tr> <td>张三</td> <td>28</td> <td>设计师</td> </tr> <tr> <td>李四</td> <td>32</td> <td>开发工程师</td> </tr> <tr> <td>王五</td> <td>25</td> <td>产品经理</td> </tr> </tbody> </table>
CSS 样式
/* 表格基础样式 */ table { border-collapse: collapse; width: 80%; margin: 20px auto; } th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; /* 过渡效果:背景色变化时长0.3秒,缓动曲线 */ transition: background-color 0.3s ease; } /* 表头样式优化 */ thead th { background-color: #f8f9fa; font-weight: 600; } /* 整列悬停效果:针对第1列 */ table:has(th:nth-child(1):hover, td:nth-child(1):hover) th:nth-child(1), table:has(th:nth-child(1):hover, td:nth-child(1):hover) td:nth-child(1) { background-color: #f1f3f5; } /* 第2列悬停 */ table:has(th:nth-child(2):hover, td:nth-child(2):hover) th:nth-child(2), table:has(th:nth-child(2):hover, td:nth-child(2):hover) td:nth-child(2) { background-color: #f1f3f5; } /* 第3列悬停 */ table:has(th:nth-child(3):hover, td:nth-child(3):hover) th:nth-child(3), table:has(th:nth-child(3):hover, td:nth-child(3):hover) td:nth-child(3) { background-color: #f1f3f5; }
注::has()选择器支持Chrome 105+、Firefox 121+、Safari 15.4+,若需兼容旧浏览器,使用下面的JavaScript方案。
二、JavaScript兼容方案(支持所有浏览器)
通过监听单元格的鼠标进入/离开事件,给对应列的所有单元格添加/移除样式类:
HTML 结构
与上述HTML结构一致
CSS 样式
table { border-collapse: collapse; width: 80%; margin: 20px auto; } th, td { padding: 12px 15px; text-align: left; border-bottom: 1px solid #eee; transition: background-color 0.3s ease; } thead th { background-color: #f8f9fa; font-weight: 600; } /* 悬停时的背景色样式 */ .column-hover { background-color: #f1f3f5; }
JavaScript 代码
// 获取所有表头和数据单元格 const allCells = document.querySelectorAll('th, td'); allCells.forEach(cell => { // 获取当前单元格的列索引(从0开始) const columnIndex = cell.cellIndex; // 鼠标进入时,给对应列的所有单元格添加hover类 cell.addEventListener('mouseenter', () => { document.querySelectorAll(`th:nth-child(${columnIndex + 1}), td:nth-child(${columnIndex + 1})`) .forEach(el => el.classList.add('column-hover')); }); // 鼠标离开时,移除hover类 cell.addEventListener('mouseleave', () => { document.querySelectorAll(`th:nth-child(${columnIndex + 1}), td:nth-child(${columnIndex + 1})`) .forEach(el => el.classList.remove('column-hover')); }); });
内容的提问来源于stack exchange,提问作者Usama Riaz
相关产品推荐
相关产品推荐

