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

如何为DataTable实现每4行一组的条纹样式?

实现DataTable每4行一组的条纹样式

要替代默认table-striped的逐行交替效果,用CSS的:nth-child()选择器就能轻松实现每4行一组的条纹样式,全程不用额外JS,步骤如下:

1. 调整表格类

先把表格上的table-striped移除,避免默认样式和自定义样式冲突:

<table id="period_table" class="table table-bordered table-hover table-condensed table-sm display nowrap display compact" cellspacing="0" width="100%">
  <thead>
    <tr>
      <th>Date</th>
      <th>Name</th>
      <th>Number</th>
      <th>Price</th>
    </tr>
  </thead>
</table>

2. 编写自定义CSS

用结构化伪类选择器选中每8行里的前4行(第1-4、9-12...行)设置灰色背景,剩下的4行保留默认白色:

/* 为DataTabletbody行设置4行一组的条纹 */
#period_table tbody tr:nth-child(8n+1),
#period_table tbody tr:nth-child(8n+2),
#period_table tbody tr:nth-child(8n+3),
#period_table tbody tr:nth-child(8n+4) {
  background-color: #f5f5f5; /* 和默认table-striped灰色一致,可按需调整 */
}

/* 保留hover效果,和默认表格行为一致 */
#period_table tbody tr:hover {
  background-color: #f1f1f1;
}

原理说明

  • 8n+1到8n+4:每8行形成一个循环周期,前4行设灰色,后4行用表格默认白色,刚好实现4行一组的交替效果。
  • 仅针对tbody的tr设置,不会影响表头样式。
  • 不管DataTable是分页、排序还是搜索后动态渲染行,这个CSS规则都会自动适配,因为它是基于DOM元素的位置匹配的。

可选:保留table-striped类的兼容写法

如果不想移除table-striped,可以用更具体的选择器强制覆盖默认样式:

#period_table.table-striped tbody tr:nth-child(8n+1),
#period_table.table-striped tbody tr:nth-child(8n+2),
#period_table.table-striped tbody tr:nth-child(8n+3),
#period_table.table-striped tbody tr:nth-child(8n+4) {
  background-color: #f5f5f5;
}

#period_table.table-striped tbody tr:nth-child(8n+5),
#period_table.table-striped tbody tr:nth-child(8n+6),
#period_table.table-striped tbody tr:nth-child(8n+7),
#period_table.table-striped tbody tr:nth-child(8n+8) {
  background-color: #ffffff;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 20:42:12