【发布时间】:2015-10-31 04:57:43
【问题描述】:
有没有办法例如使用这样的 css 代码来定位第 5 个 .slide 元素:
HTML
<div id="slides">
<section>
<div class='slide'></div> this should be 1
<div class='slide'></div> this should be 2
<div class='slide'></div> this should be 3
</section>
<section>
<div class='slide'></div> this should be 4
</section>
<section>
<div class='slide'></div> this should be 5 I target this one
<div class='slide'></div> this should be 6
<div class='slide'></div> this should be 7
</section>
</div>
CSS
.slide:nth-of-type(5) {
background:red;
}
我认为这样的事情会奏效,但没有。
我基本上想用相应的数字访问每个元素,所以第 7 个在 css 中有一个 7
如果需要,我愿意接受 jquery 解决方案
【问题讨论】:
-
我想你可以在 CSS4 中使用
match执行此操作,尽管目前尚不支持。 -
恐怕如果没有 JQuery,您将无法选择该元素。由于 div 都有不同的父级,因此您将无法使用
nth-之类的选择器来选择它们。 Jquery 可以做到这一点,因为它可以计算所有.slide元素,而不是选择第 5 个元素。 -
@Bram Vanroy:不。该站点甚至语法错误(而且整个内容看起来写得不太好)-
p:nth-match(2n+1)实际上等同于p:nth-child(2n+1)。它应该是:nth-match(2n+1 of p),即使那样,它也等同于p:nth-of-type(2n+1),尽管它的名字可能暗示了什么。这就是 CSSWG got rid of that name altogether 的原因。 -
@BoltClock 感谢您的澄清。我想我应该总是在发表声明之前检查官方文档。
标签: html css css-selectors