使用:nth-child和:not进行CSS样式设置

3

我有一个

元素列表,我想使用nth-child选择器对它们进行样式设置。同时,如果某个
元素具有特定的类,请将其排除在外,例如:

<style>
 .a:not(.b):nth-child(2n) {
    color: hotpink;
 }
</style>

<div class="a"> Test </div>
<div class="a b"> Test </div>
<div class="a"> I should be pink, as i am the 2nd child that doesnt have a "b" class </div>
<div class="a"> Test </div>
<div class="a"> Test </div>
<div class="a"> Test </div>
<div class="a"> Test </div>
<div class="a"> Test </div>
<div class="a"> Test </div>

http://jsfiddle.net/BF7GY/


1
如果您描述清楚您尝试通过这个来实现什么,可能会有更简单的方法。如果使用JavaScript是一个选项,那也非常容易。 - Kayo
2
据我所知,目前的 CSS 伪类并不支持这种操作。nth-child 和其他类似的选择器是按照它们的子元素索引进行匹配的,而不是带有 .x 类的子元素索引。 - Andy
我实际上想要做的是为Windows 8 ListView设置样式,当鼠标按下某个项目时,它会注入一个隐藏的div,进而重新着色列表的其余部分。 - Andy
1个回答

3
我认为最好的方法是使用jQuery和两个filter()调用,例如:
$('.a').filter(function(){
        return !$(this).hasClass('b');
     }).filter(
    function(i){
        return (i+1)%2 == 0; 
    }
).css('color','hotpink');

:not和:nth-child并不像我们希望的那样灵活(遗憾的是)


似乎这是前进的道路,可惜真遗憾。 - Andy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接