使用CSS3选择类的所有其他元素 [英] Select every other element of class using css3

查看:230
本文介绍了使用CSS3选择类的所有其他元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出具有以下结构的ul:

<ul>
    <li class="product">...</li>
    <li class="product">...</li>
    <li class="product">...</li>
    <li class="product">...</li>
    <li class="spot">...</li>
    <li class="product">...</li>
    <li class="product">...</li>
</ul>

是否可以使用CSS3定位类产品中li的其他所有出现.

Is there any way using CSS3 to target every other occurance of a li with the class product.

我尝试在各种配置中同时使用nth-of-child和nth-of-type来避免碰运气,无论类是否具有,两者似乎都以其他li元素为目标.

I've tried using both nth-of-child and nth-of-type in various configurations to no luck, both seem to target every other li element regardless of the class is has.

推荐答案

使用纯CSS不能做到这一点(以我所知道的任何方式),但是纯JavaScript解决方案非常简单:

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小提琴演示.

jQuery(大概可以使用任何 other JavaScript库),但是肯定不是必需的.

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

这篇关于使用CSS3选择类的所有其他元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆