html - Css nth-child 忽略 div - javascript nth-child 等同于表亲元素

标签 html css css-selectors

我正在寻找一个选择器,它可以像第 n 个子选择器一样工作,但不会在每个新的 div 上重置。这就是我的意思:

#yellow p:nth-child(3n) {
  background-color: yellow;
}
<!DOCTYPE html>
<html>

<body>

  <div id="yellow">
    <div>
      <p>This should not be yellow.</p>
      <p>This should not be yellow.</p>
    </div>

    <br>

    <div>
      <p>This should be yellow.</p>
      <p>This should not be yellow.</p>
    </div>
  </div>

</body>

</html>

如果您运行前面的代码片段,则所有 p 标记都不会变为黄色,因为第 n 个子选择器中的 3n 计数器会在第二个 div 标记处“重新启动”。我正在寻找一个忽略这一点的选择器,并简单地将 css 应用于 #yellow div 中的每个第 3 个 p 元素(不管任何其他封装标签)。

是否存在这样的选择器,如果不存在,我可以使用哪些其他替代方案(可能是 jquery/js)? 谢谢!

最佳答案

:nth-child():nth-of-type() 对 sibling 进行操作,因此针对所有 p'页面上的 s 不能一起工作,因为它们不是 sibling 。

要针对该段落,我会针对您想要的 div 并在该 div 中使用 :nth-child() 来选择p 相对于它的 sibling 。

#yellow div:last-child p:first-child {
  background-color: yellow;
}
  <div id="yellow">
    <div>
      <p>This should not be yellow.</p>
      <p>This should not be yellow.</p>
    </div>

    <br>

    <div>
      <p>This should be yellow.</p>
      <p>This should not be yellow.</p>
    </div>
  </div>

要在 JS/jquery 中执行此操作,您只需获取 #yellow 的子级的所有 p 并定位第三个。

$('#yellow p').eq(2).css('background','yellow');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="yellow">
    <div>
      <p>This should not be yellow.</p>
      <p>This should not be yellow.</p>
    </div>

    <br>

    <div>
      <p>This should be yellow.</p>
      <p>This should not be yellow.</p>
    </div>
  </div>

关于html - Css nth-child 忽略 div - javascript nth-child 等同于表亲元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44219836/

相关文章:

Jquery如何设置事件链接的CSS颜色

jquery - 为什么这个 jquery 选择器不能识别这些图像

java - 我如何使 JTIdy 使 HTML 文档格式正确?

html - div响应中的对齐图像

javascript - 右列高度等于左列

html - 在 css 中使用 * 选择器,但排除 h1?

CSS Child 与后代选择器

javascript - 如何在源于grails服务的textarea中显示换行符?

jquery - 我可以从 jquery 函数创建 ember 计算属性吗?

javascript - 你如何设置滚动条位置