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

如何全局选择第n个子元素?让所有奇数位<span>元素变红

全局选中跨父元素的奇数位<span>解决方案

CSS的nth-child(odd)仅在父元素范围内计数,无法实现跨父元素的全局奇偶选择,以下是两种可行方法:

方法一:JavaScript 辅助(通用兼容)

通过JS遍历所有<span>,按全局顺序为奇数位元素添加类,再用CSS设置样式:

const spans = document.querySelectorAll('span');
spans.forEach((el, idx) => {
  if ((idx + 1) % 2 === 1) { // 全局序号从1开始,idx为0索引
    el.classList.add('global-odd');
  }
});
.global-odd {
  color: red;
}

/* 保留你的计数器样式 */
body {
  counter-reset: spans;
}

span {
  counter-increment: spans;
}

span::after {
  content: counter(spans);
}

方法二:CSS :has() 选择器(仅现代浏览器)

如果目标浏览器支持:has()(Chrome 101+、Firefox 121+),可以针对固定结构的HTML写组合选择器,但结构变化时需要同步修改:

针对你提供的HTML结构,全局奇数位的<span>对应的选择器:

div:first-child > span,
div:nth-child(2) > span:first-child,
div:nth-child(3) > span:nth-child(2),
div:nth-child(4) > span:nth-child(2),
div:nth-child(4) > span:nth-child(4) {
  color: red;
}

/* 保留计数器样式 */
body {
  counter-reset: spans;
}

span {
  counter-increment: spans;
}

span::after {
  content: counter(spans);
}

这种方法局限性大,仅适合结构固定的场景,更推荐方法一。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 11:35:20