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

如何为特定class行之后的奇数序号表格行添加背景色?

实现带区块表头的表格隔行着色(区块首行必着色)

由于CSS无法直接对兄弟元素进行分组计数,纯CSS方案存在兼容性和灵活性局限,更推荐用JavaScript实现每个区块内独立的隔行着色需求:

完整代码示例

HTML(无需手动添加want类)

<table>
  <tr class="table-header"><th>Blah</th><th>Blablablah</th></tr>
  <tr class="section-header"><th colspan="2">Section A</th></tr>
  <tr class="regular-row"><td>A1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>A2</td><td>Blah</td></tr>
  <tr class="regular-row"><td>A3</td><td>Blah</td></tr>
  <tr class="regular-row"><td>A4</td><td>Blah</td></tr>
  <tr class="regular-row"><td>A5</td><td>Blah</td></tr>
  <tr class="section-header"><th colspan="2">Section B</th></tr>
  <tr class="regular-row"><td>B1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>B2</td><td>Blah</td></tr>
  <tr class="regular-row"><td>B3</td><td>Blah</td></tr>
  <tr class="regular-row"><td>B4</td><td>Blah</td></tr>
  <tr class="section-header"><th colspan="2">Section C</th></tr>
  <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
  <tr class="section-header"><th colspan="2">Section D</th></tr>
  <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
  <tr class="regular-row"><td>C1</td><td>Blah</td></tr>
</table>

CSS

table {
  border-collapse: collapse;
}

.want {
  background-color: aquamarine;
}

JavaScript

// 遍历所有区块表头
document.querySelectorAll('.section-header').forEach(header => {
  let currentRow = header.nextElementSibling;
  let rowIndex = 1; // 从1开始计数,奇数行添加着色类
  
  // 遍历当前区块下的所有普通行,直到遇到下一个区块表头或表格结束
  while (currentRow && currentRow.classList.contains('regular-row')) {
    if (rowIndex % 2 === 1) {
      currentRow.classList.add('want');
    }
    currentRow = currentRow.nextElementSibling;
    rowIndex++;
  }
});

实现逻辑

  1. 定位所有区块表头元素,逐个处理其后续的普通行
  2. 对每个区块内的普通行独立计数,奇数位置的行自动添加着色类
  3. 当遇到下一个区块表头或表格末尾时,停止当前区块处理,自动启动下一个区块的计数流程

内容的提问来源于stack exchange,提问作者Gaetan L.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:45:29