如何使用inline CSS实现HTML表格行鼠标悬停时背景变色
解决方案
纯行内CSS无法支持:hover伪类,你可以通过给<tr>添加行内鼠标事件实现需求,所有逻辑都内嵌在标签属性内,无需额外style块或全局脚本,且能自动恢复各td原有颜色。
场景1:td背景色直接写在行内style属性中
<table border="1"> <tr onmouseover="Array.from(this.children).forEach(td => { td.dataset.oldBg = td.style.backgroundColor; td.style.backgroundColor = 'pink'; })" onmouseout="Array.from(this.children).forEach(td => { td.style.backgroundColor = td.dataset.oldBg; })" > <td style="background-color: #e3f2fd">列1(浅蓝)</td> <td style="background-color: #f3e5f5">列2(浅紫)</td> <td style="background-color: #e8f5e9">列3(浅绿)</td> </tr> <tr onmouseover="Array.from(this.children).forEach(td => { td.dataset.oldBg = td.style.backgroundColor; td.style.backgroundColor = 'pink'; })" onmouseout="Array.from(this.children).forEach(td => { td.style.backgroundColor = td.dataset.oldBg; })" > <td style="background-color: #e3f2fd">列1内容2</td> <td style="background-color: #f3e5f5">列2内容2</td> <td style="background-color: #e8f5e9">列3内容2</td> </tr> </table>
场景2:td背景色通过CSS类定义(通用方案)
如果你的td颜色是分配的CSS类实现的,用这个版本的事件逻辑即可:
<tr onmouseover="Array.from(this.children).forEach(td => { td.style.backgroundColor = 'pink'; })" onmouseout="Array.from(this.children).forEach(td => { td.style.backgroundColor = ''; })" > <td class="col-blue">列1(类定义蓝色)</td> <td class="col-purple">列2(类定义紫色)</td> <td class="col-green">列3(类定义绿色)</td> </tr>
实现逻辑
- 所有逻辑都写在
<tr>的行内事件属性中,完全适配不支持自定义style块、不允许插入全局脚本的CMS环境 - 悬停时直接给td设置行内背景色(优先级高于类样式),悬停结束后清空td的行内背景色设置,自动恢复原有类或行内定义的颜色,无需提前记录每个td的色值,适配任意列色区分的表格
内容的提问来源于stack exchange,提问作者markling
相关产品推荐
相关产品推荐

