You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用CSS伪选择器实现两个表格的联动高亮效果?

双表格联动高亮实现方案

纯CSS实现的局限性与可行场景

纯CSS没办法动态获取悬停行的索引来匹配另一表格的对应行,只有当两个表格是同级紧邻DOM元素,且行数固定时,才能通过硬写:nth-child()伪类实现,但实用性极低——比如固定两行的情况:

/* 仅针对固定行数的硬编码示例,扩展性差 */
.sticky-table tbody tr:nth-child(1):hover td,
.sticky-table tbody tr:nth-child(1):hover ~ .auto-number-table tbody tr:nth-child(1) td {
  background-color: #e0e0e0;
}
.sticky-table tbody tr:nth-child(2):hover td,
.sticky-table tbody tr:nth-child(2):hover ~ .auto-number-table tbody tr:nth-child(2) td {
  background-color: #e0e0e0;
}

注:这种方案只能应付固定行数的表格,一旦新增或删除行,就得修改CSS,完全不适合动态数据场景。

事件处理器+CSS类的实用方案

这是最靠谱的实现方式,通过JS监听悬停事件标记对应行,再用CSS控制高亮样式:

1. 给对应行添加索引标识

给两个表格的每一行加上相同的data-row-index属性,确保行对应关系:

<!-- 数据表格 -->
<table class="sticky-table">
  <tbody>
    <tr data-row-index="0">
      <td>第一行数据</td>
    </tr>
    <tr data-row-index="1">
      <td>第二行数据</td>
    </tr>
  </tbody>
</table>

<!-- 自动编号表格 -->
<table class="auto-number-table">
  <tbody>
    <tr data-row-index="0">
      <td>1</td>
    </tr>
    <tr data-row-index="1">
      <td>2</td>
    </tr>
  </tbody>
</table>

2. 编写CSS高亮样式

.highlight td {
  background-color: #e0e0e0;
}

3. 添加JS事件监听

// 获取所有表格行
const stickyRows = document.querySelectorAll('.sticky-table tbody tr');
const numberRows = document.querySelectorAll('.auto-number-table tbody tr');

// 数据表格悬停联动
stickyRows.forEach(row => {
  row.addEventListener('mouseenter', () => {
    const idx = row.dataset.rowIndex;
    row.classList.add('highlight');
    document.querySelector(`.auto-number-table tr[data-row-index="${idx}"]`).classList.add('highlight');
  });
  row.addEventListener('mouseleave', () => {
    const idx = row.dataset.rowIndex;
    row.classList.remove('highlight');
    document.querySelector(`.auto-number-table tr[data-row-index="${idx}"]`).classList.remove('highlight');
  });
});

// 编号表格悬停联动
numberRows.forEach(row => {
  row.addEventListener('mouseenter', () => {
    const idx = row.dataset.rowIndex;
    row.classList.add('highlight');
    document.querySelector(`.sticky-table tr[data-row-index="${idx}"]`).classList.add('highlight');
  });
  row.addEventListener('mouseleave', () => {
    const idx = row.dataset.rowIndex;
    row.classList.remove('highlight');
    document.querySelector(`.sticky-table tr[data-row-index="${idx}"]`).classList.remove('highlight');
  });
});

优化建议

如果表格行数较多,建议用事件委托减少事件绑定数量,比如给表格tbody绑定事件,通过事件目标找到对应行:

// 事件委托示例(数据表格)
document.querySelector('.sticky-table tbody').addEventListener('mouseenter', (e) => {
  const row = e.target.closest('tr');
  if (!row) return;
  const idx = row.dataset.rowIndex;
  row.classList.add('highlight');
  document.querySelector(`.auto-number-table tr[data-row-index="${idx}"]`).classList.add('highlight');
});
// mouseleave事件同理

内容的提问来源于stack exchange,提问作者Code Master

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 02:05:05