使用jquery作为css nth child的替代品

JCH*_*E11 2 jquery parent-child css3

我使用以下css创建具有chckerboard背景的列表项(每个其他列表项具有灰色背景,每行移动以创建棋盘图案:

li:nth-child(8n+2), li:nth-child(8n+4), li:nth-child(8n+5), li:nth-child(8n+7) {
    background-color:grey;
}
Run Code Online (Sandbox Code Playgroud)

有没有办法可以使用比css3更支持的jquery来做到这一点?谢谢

Nic*_*ver 7

简答:是的!

只需将它用作a中的选择器document.ready,它就可以跨浏览器工作,如下所示:

$(function() {
  $("li:nth-child(8n+2), li:nth-child(8n+4), li:nth-child(8n+5), li:nth-child(8n+7)")
    .css('background-color','grey');
});
Run Code Online (Sandbox Code Playgroud)

注意:这会在运行时运行的元素上运行,如果您是动态添加/删除元素,则只需调用相同的选择器.css().在这种情况下我会推荐一个班级,所以不是.css('background-color','grey'),你有.addClass('myClass')