如果我有类似的HTML,如何在id="container"的div内交替(偶数和奇数)替换div的样式(jquery的背景色)
<div id="container">
<div></div>
<div></div>
<div></div>
<div></div>
...
</div>
我知道这样的桌子
$('#container>div:odd').css("background-color", "#ff0000");
$('#container>div:even').css("background-color", "#00ff00");
但是所有的divs都应该有不同的颜色。。。?任何div都不应该具有相同的颜色。。有人能帮我吗.
试试这个:
var colors = ["f00", "0f0", "00f", "ff0", "0ff", "f0f"];
$('#someid .bar').each(function(i) {
$(this).css('background-color', '#'+colors[i % colors.length]);
});
对于随机颜色,您可以使用以下选项:
function randomColor() {
return 'rgb('+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+', '+
Math.round(Math.random()*255)+')'
}
$('#someid .bar').each(function(i) {
$(this).css('background-color', randomColor());
});
演示:
http://jsbin.com/eqoyi4