开发者

Styling Nested list elements

I want to style alternate item in a list with a background color of gray. However, if there are nested li elements, the styling goes wrong, and consecutive elements in the nested list get styled the same color of gray.

Any idea on how to style them alternate gray, even the nested ones, using css/jquery?

Edit

<div id='wrapper'>

<ul>

<li class='comment'><div class='aut'>the_archer</div><div class='comment-body'>Test</div><div class='timestamp'>2011-02-15 17:22:11</div><a href='#comment_form' class='reply' id='7'>Reply</a><ul><li class='comment'><div class='aut'>great</div><div class='comment-body'>t</div><div class='timestamp'>2011-02-15 17:38:43</div><a href='#comment_form' class='reply' id='8'>Reply</a><ul><li class='comment'><div class='aut'>test</div><div class='comment-body'>eee</div><div class='timestamp'>2011-02-15 17:40:21</div><a href='#comment_form' class='reply' id='10'>Reply</a><ul><li class='comment'><div class='aut'>fook</div><div class='comment-body'>kkk</div><div class='timestamp'>2011-02-15 18:07:08</div><a href='#comment_form' class='reply' id='12'>Reply</a></li></ul></li><li class='comment'><div class='aut'>Anonymouse</div><div class='comment-body'>dsdsd</div><div class='timestamp'>2011-02-15 17:44:53</div><a href='#comment_fo开发者_Python百科rm' class='reply' id='11'>Reply</a></li><li class='comment'><div class='aut'>bbbb</div><div class='comment-body'>bbbb</div><div class='timestamp'>2011-02-15 18:32:23</div><a href='#comment_form' class='reply' id='14'>Reply</a></li></ul></li><li class='comment'><div class='aut'>w</div><div class='comment-body'>www</div><div class='timestamp'>2011-02-15 17:39:29</div><a href='#comment_form' class='reply' id='9'>Reply</a></li></ul></li><li class='comment'><div class='aut'>t</div><div class='comment-body'>t</div><div class='timestamp'>2011-02-15 18:30:09</div><a href='#comment_form' class='reply' id='13'>Reply</a></li></ul>

</div>

CSS:

.comment-style{background: gray;}

Jquery

$('ul li.comment:odd').addClass('comment-style');


Live Demo

Changed JQuery:

$('li.comment:odd').css("background-color", "gray");
$('li.comment:even').css("background-color", "white");


In addition to Myles' answer, you can use css3 selectors to select odd elements.

li.comment:nth-child(2) { background:gray; }

It's supported in most modern browsers except for IE8 (IE9 is supposed to support it though.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜