You need to enable JavaScript to run this app. 如何为奇偶次序的class=row元素下的子div设置不同背景色
优惠活动
大模型
产品
解决方案
定价
更多

如何为奇偶次序的class=row元素下的子div设置不同背景色

解决方案

方案1:纯CSS实现(推荐,无需修改原有HTML)

无需改动你现有的HTML结构,仅新增以下CSS规则即可实现需求:

/* CSS :nth-child 计数从1开始 */
/* 匹配所有奇数位的.row元素,子div设为蓝色 */
.row:nth-child(odd) > div {
  background: blue;
}
/* 匹配所有偶数位的.row元素,子div设为红色 */
.row:nth-child(even) > div {
  background: red;
}

如果你需要调整奇偶对应的颜色,直接交换两个规则里的background属性值即可。

方案2:JavaScript动态添加内联样式

如果你的业务场景要求必须将样式写在行内style属性中,可使用以下JS代码实现:

const allRows = document.querySelectorAll('.row');
allRows.forEach((row, idx) => {
  // idx从0开始计数,偶数下标对应奇数位row,和你给出的示例效果匹配
  const targetColor = idx % 2 === 0 ? 'blue' : 'red';
  row.querySelectorAll('div').forEach(child => {
    child.style.background = targetColor;
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 12:06:13