是否有可能使用目前的浏览器使用伪类检测第一个和最后一个特定类的?(Is it possible us

2019-06-23 19:00发布

如果你有HTML:

<section class="column">
  <p> Some Test </p>
  <p> Some Test </p>
  <p> Some Test </p>
</section>

<section class="column">
  <p> Some More Test </p>
  <p> Some More Test </p>
  <p> Some More Test </p>
</section>

<section class="someotherclass">
  <p> Some More Test </p>
  <p> Some More Test </p>
  <p> Some More Test </p>
</section>

和CSS:

.column:last-child { background:red; }

http://jsfiddle.net/WYu24/

有没有一种方法,使:last-child选择拿起一类的最后一次出现?

Answer 1:

目前没有捷径语法或伪类CSS中寻找具有一定阶级的第一个或最后一个孩子。 1

我用一个压倒一切的技术样式的第一个孩子具有一定的阶级,这是我在重详细描述了这个答案 。 然而,由于兄弟姐妹组合程序是如何工作的,这种技术不能适用于具有一定阶级的最后一个孩子 。

我不知道任何纯CSS方式靶向具有某一类的最后一个孩子。 你必须使用JavaScript或者调整你的标记才能做到这一点。 如果恰好有一个这样的元素,然后使用jQuery,你可以简单地使用:last选择添加类,然后你可以CSS样式:

$('.column:last').addClass('last');
.column.last { background:red; }

的jsfiddle预览


1 有一些新的伪类的选择器4提议这将符合该法案,但浏览器不会开始实施它的另一个几个月,直到规范是更稳定,而且当时我们不知道这些伪-班是要坚持,因为当前的语法看起来相当尴尬:

:nth-last-match(1 of .column) { background:red; }


文章来源: Is it possible using current browsers to use pseudo-classes to detect first and last of a certain class?