【问题标题】:":first-of-type" works, ":last-of-type" doesn't":first-of-type" 有效,":last-of-type" 无效
【发布时间】:2011-12-24 04:04:37
【问题描述】:

下面的 ":first-of-type" 对我有用,但 ":last-of-type" 不行。

<div class="wrapper">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
    <div class="shadow"></div>
</div>

.wrapper .item:first-of-type {
    background-color: blue;
}
.wrapper .item:last-of-type {
    background-color: red;
}

即使通过 jQuery 计算元素的数量,我也会收到以下结果:

$('.wrapper .item').size(); // equals 3
$('.wrapper .item:first-of-type').size(); // equals 1
$('.wrapper .item:last-of-type').size(); // equals 0

提前谢谢你。

【问题讨论】:

    标签: jquery html css pseudo-class


    【解决方案1】:

    它们都适合我,但你应该知道 jQuery 不支持 first-of-typelast-of-type

    它们完全起作用是因为querySelectorAll 支持它们。所以不支持qSA的浏览器会崩溃。


    顺便说一句,您的0 结果来自first/last-of-type 考虑元素类型,即使您只指定了类。我的测试有点不同。

    【讨论】:

    • 我只是用jQuery来测试;我只担心CSS。但是我仍然无法让 ":last-of-type" 工作。对于具体示例,您可以查看此处 - apps.ryanprentiss.com/osiris/?m=20111218。在 style.css 中有一个根本不会注册的“.archiveWrapper .archiveItem:last-of-type”样式。当更改为 ":first-of-type" 时,它可以工作。
    • @RyanPrentiss:是的,请查看答案中的最后一句话。 -of-type 选择器将考虑元素的 type。如果您将&lt;div class="shadow"&gt;&lt;/div&gt; 更改为&lt;p class="shadow"&gt;&lt;/p&gt;,它应该可以工作。
    【解决方案2】:

    jQuery 不支持 :last-of-type - http://selectivizr.com/ - 查看库比较表。你可能想看看这个插件来帮助你 - https://github.com/keithclark/JQuery-Extended-Selectors

    【讨论】:

    • 我只是用jQuery来测试;我只担心 CSS。
    【解决方案3】:

    为什么不使用first()last()?前者选择匹配集中的第一个元素,后者选择最后一个元素。

    Here 是与:first:last-of-type 相关的错误报告。

    【讨论】:

    • 我只是用jQuery来测试;我只担心 CSS。
    猜你喜欢
    • 1970-01-01
    • 2011-08-04
    • 2021-12-20
    • 2011-07-06
    • 2018-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-03-04
    • 2014-08-30
    相关资源
    最近更新 更多