Select every other element of class using css3

后端 未结 3 632
夕颜
夕颜 2021-01-12 11:08

Given an ul with a structure like this:

  • ...
  • ...
相关标签:
3条回答
  • 2021-01-12 11:32

    This cannot be done with plain CSS (in any way that I yet know of), however a plain-JavaScript solution is pretty simple:

    var​ lis = document.querySelectorAll('li.product');
    
    for (var i=0,len=lis.length;i<len;i++){
        if (i%2 == 0){
            lis[i].className = 'oddProduct';
        }
    }​
    

    JS Fiddle demo.

    jQuery could be used instead (as could, presumably, any other JavaScript library), but it's certainly not required.

    0 讨论(0)
  • 2021-01-12 11:42

    Basically, you can't with plain CSS3. The nth-child selectors work on element selectors, not classes. So, li:nth-child(even) works, but .product:nth-child(even) does not.

    You will need jQuery to achieve this.

    0 讨论(0)
  • 2021-01-12 11:52

    Could your problem be solved by overriding spot and selecting every other li (like others have mentioned)? Also, you could select the ul by class name.

    How is this:

    .ul_class li:nth-child(even) {
        background: #CCC;
    }
    
    .spot {
        background: green;
    }
    

    The only glitch that might end up looking odd is when 2 spot li`s are right next to each other. I think in every other case spot should look fine.

    I also found that this worked fine in chrome:

    li.product:nth-child(even) {
        background: #ccc;
    }
    
    0 讨论(0)
提交回复
热议问题