如何基于Bootstrap表格单元格值动态修改table-hover的hover颜色
基于表格状态列动态设置hover行背景色
实现方案
1. 给表格行绑定状态类
先给每个表格行<tr>添加对应状态的类,比如status-late对应LATE、status-early对应EARLY、status-on-time对应ON TIME,修改后的HTML代码如下:
<table class="table table-hover"> <thead> <tr> <th scope="col">Fleet</th> <th scope="col">Location</th> <th scope="col">Status</th> </tr> </thead> <tbody> <tr class="status-on-time"> <th scope="row">R132</th> <td>High St</td> <td>ON TIME</td> </tr> <tr class="status-late"> <th scope="row">R100</th> <td>St Martins</td> <td>LATE</td> </tr> <tr class="status-early"> <th scope="row">W101</th> <td>Cafe St</td> <td>EARLY</td> </tr> </tbody> </table>
2. 编写状态对应的hover样式
通过CSS类选择器,针对不同状态的行设置hover背景色,同时覆盖Bootstrap默认的table-hover样式,确保优先级足够:
/* LATE状态hover色:浅红 */ .table-hover tbody tr.status-late:hover td, .table-hover tbody tr.status-late:hover th { background-color: #ffcccc; } /* EARLY状态hover色:浅绿 */ .table-hover tbody tr.status-early:hover td, .table-hover tbody tr.status-early:hover th { background-color: #ccffcc; } /* ON TIME状态保持默认hover色 */ .table-hover tbody tr.status-on-time:hover td, .table-hover tbody tr.status-on-time:hover th { background-color: #f8f9fa; }
3. 动态绑定状态类(数据驱动场景适用)
如果表格是后端渲染或JS动态生成的,可以用脚本自动给行添加状态类,不用手动写:
const tableRows = document.querySelectorAll('.table-hover tbody tr'); tableRows.forEach(row => { const statusText = row.querySelector('td:last-child').textContent.trim(); // 把状态文本转成合法的类名格式 const statusClass = `status-${statusText.toLowerCase().replace(' ', '-')}`; row.classList.add(statusClass); });
说明
这种方式既保留了Bootstrap表格的原有风格,又精准实现了按状态动态切换hover背景色的需求,颜色值可根据实际视觉需求自行调整。
内容的提问来源于stack exchange,提问作者user3788685
相关产品推荐
相关产品推荐

