css样式使用:nth-​​child和:not

时间:2012-12-18 09:36:27

标签: html css css3 css-selectors

我有一个div的列表,我希望使用nth-child选择器设置样式。如果它有某个类,我也希望能够排除div,即:

<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 个答案:

答案 0 :(得分:3)

我认为最好的方法是使用jQuery和两个filter()调用,如:

$('.a').filter(function(){
        return !$(this).hasClass('b');
     }).filter(
    function(i){
        return (i+1)%2 == 0; 
    }
).css('color','hotpink');

:not and:nth-​​child不如我们想要的那样灵活(不幸的是)