是否有可能使用当前浏览器使用伪类来检测某个类的第一个和最后一个? [英] Is it possible using current browsers to use pseudo-classes to detect first and last of a certain class?

查看:115
本文介绍了是否有可能使用当前浏览器使用伪类来检测某个类的第一个和最后一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有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 选择器接受类的最后一次出现?

Is there a way to make the :last-child selector pick up the last occurrence of a class?

推荐答案

目前没有快捷方式语法或伪类在CSS中找到有某个类的第一个或最后一个孩子。 1

Currently there is no shortcut syntax or pseudo-class in CSS for finding the first or last child having a certain class.1

我使用覆盖技术类,我在此答案中详细描述。但是,由于同胞组合器的工作方式,此技术无法应用于最后一个具有特定类别的孩子。

I use an overriding technique to style the first child with a certain class, which I describe in heavy detail in this answer. However, due to how sibling combinators work, this technique cannot be applied for the last child having a certain class.

我不知道有什么纯CSS方法来定位最后一个有某个类的孩子。你必须使用JavaScript或重组你的标记为了做到这一点。如果只有一个这样的元素,那么使用jQuery你可以简单地使用:last 选择器添加一个类,然后你可以使用CSS样式:

I do not know of any pure CSS way to target the last child having a certain class. You have to use JavaScript or restructure your markup in order to do that. If there is exactly one such element, then using jQuery you can simply use the :last selector to add a class, which you can then style with CSS:

$('.column:last').addClass('last');





.column.last { background:red; }

jsFiddle预览

1 一些在选择器4中提出的新伪类将适合bill,但浏览器不会开始实现它几个月或规范更稳定,即使我们不知道这些伪类是否会坚持,因为当前语法看起来相当尴尬:

1 There are some new pseudo-classes being proposed in Selectors 4 which would fit the bill, but browsers won't start implementing it for another few months or until the spec is more stable, and even then we don't know if these pseudo-classes are going to stick because the current syntax looks rather awkward:

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

这篇关于是否有可能使用当前浏览器使用伪类来检测某个类的第一个和最后一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆