如何为一个div内部的另一个div交替应用样式(背景颜色)

4
如何使用jQuery为ID为“container”的div内的div交替(偶数和奇数)设置样式(背景颜色)?如果我有以下HTML代码:
<div id="container">
   <div></div> 
   <div></div>
   <div></div>
   <div></div>
...
</div>

我知道表格的格式是这样的:
#tbl_users tr:nth-child(even) {background: #CCC;}
#tbl_users tr:nth-child(odd) {background: #FFF;}

但是如何将类似这样的东西应用到div中呢?
5个回答

6

你尝试过以下方法吗:

div#container div:nth-child(even) {background: #CCC;}
div#container div:nth-child(odd) {background: #FFF;}

nth-child在标签不同的情况下仍应起作用。


4
$('#container>div:odd').css("background-color", "#ff0000");
$('#container>div:even').css("background-color", "#00ff00");

IE7的好解决方案! - Richard

2

对于div,它的工作方式完全相同。使用上述结构,您可以通过以下方式获得相同的效果:

#container div:nth-child(even) {background: #CCC;}
#container div:nth-child(odd) {background: #FFF;}

@pistacchio 你说得对,但他通常用于表格的CSS也不行。 - Niklas
为什么人们总是抱怨某些选择器/属性在浏览器上的支持不好,而明显很多人包括OP并不在意呢? - BoltClock

0

使用相同的技巧:

#container div:nth-child(even) {background: #CCC;}
#container div:nth-child(odd) {background: #FFF;}

0
<div id="container">
   <div>A</div> 
   <div>B</div>
   <div>C</div>
   <div>D</div>
</div>

div#container div:nth-child(even) {background: #FF00CC;}
div#container div:nth-child(odd) {background: #CC00FF;}

请尝试使用此链接 http://codebins.com/codes/home/4ldqpbz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接