:last-child / last-of-type伪困难

时间:2014-07-15 14:59:30

标签: css css3

难以尝试定位作为最后一个匹配选择器的集合中的特定元素。

<div class="items">
    <article class="today">
        this is today
    </article>
    <article class="today">
        this is today
    </article>
    <article class="today">
        this is today
    </article>
    <article>
        Not today
    </article>
    <article>
        Not today
    </article>
</div>

我的目标是重新设置最后一项article.today的样式。

article {
    background: cyan;
}

.today:last-child { 
    background: black;
    color: white;
}

它不起作用。 http://jsfiddle.net/nv54h/ 改为:

article {
    background: cyan;
}

article:last-child { 
    background: black;
    color: white;
}

确实有效,因为最后一项现在是黑色的。 http://jsfiddle.net/nv54h/1/ - 但是没有做两个循环或不同的元素,我无法按预期工作(例如,last-of-type

有什么方法可以考虑仅定位最后一个.today项目吗? list是通过实时更改的集合迭代生成的,因此仅CSS /标记解决方案是完美的,如果项n+1不是today等,则避免逻辑和反向引用。我猜{ Sizzle中的{1}}是理想的解决方案,但是......

1 个答案:

答案 0 :(得分:1)

我能想到的唯一方法是使用javascript ...

:last-child:last-of-type仅适用于元素,它们不会按照您认为的方式关注类。通过删除没有类名的两篇文章,您的代码将起作用......

http://jsfiddle.net/nv54h/2/


使用一些jQuery,您可以轻松实现这一目标:

$( "article.today:last" ).css({ backgroundColor: "yellow", fontWeight: "bolder" });

http://jsfiddle.net/nv54h/3/


更好的是,只需添加一个类。这样,您的所有样式都可以保留在样式表中。

$( "article.today:last" ).addClass('black');

http://jsfiddle.net/nv54h/4/

相关问题