我想要类似 jquery :last
选择器的东西,但在纯 css 中。
如果我不知道它在 DOM 结构中的索引,我怎么能只得到“z”段呢!。 或者如何获得“.area”类的最后一个 child ? 我看到这个 CSS3 get last element ,但它在我的情况下不起作用,因为我在父元素中有另一个 child 。
p.area:last-child
不工作!
当我们知道类 .area
有多少元素时,我找到了解决方案。
选择器看起来像这样:p.area ~ p.area ~ p.area
但是当我们不知道...我想...
只是为了好玩 =)
<div>
<h1>This is a heading</h1>
<p class="">The first paragraph.</p>
<p class="area">The x paragraph.</p>
<p class="area">The y paragraph.</p>
<p class="area">The z paragraph.</p>
<p class="">The last paragraph.</p>
</div
最佳答案
没有javascript你做不到。这是来自 the W3C spec 的引述:
Standalone text and other non-element nodes are not counted when calculating the position of an element in the list of children of its parent.
伪类目标元素无法使用组合器或简单选择器(如 id 或 class)作为目标。这些类型的伪类称为“Structural Pseudo Classes”。他们会忽略元素上有一个类这一事实,而只是使用 DOM 来确定要定位的正确元素。
在这种情况下,您唯一的选择是使用 nth-child 或 javascript 进行显式定位。
关于css - 从纯 css 中已选择的元素中选择最后一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18261892/