如何为div不同的div替换样式(背景颜色)?

Sad*_*utu 0 css jquery jquery-selectors

如果我有像这样的HTML,如何交替(偶数和奇数)替换div内的div的样式(背景颜色与jquery)div = id ="container"

<div id="container">
   <div></div> 
   <div></div>
   <div></div>
   <div></div>
...
</div>
Run Code Online (Sandbox Code Playgroud)

我知道桌子就像

  $('#container>div:odd').css("background-color", "#ff0000");
  $('#container>div:even').css("background-color", "#00ff00");
Run Code Online (Sandbox Code Playgroud)

但是所有[divs]应该有不同的颜色......?没有div应该有相同的颜色..任何人都可以帮助我..

col*_*ain 6

试试这个:

var colors = ["f00", "0f0", "00f", "ff0", "0ff", "f0f"];

$('#someid .bar').each(function(i) {
   $(this).css('background-color', '#'+colors[i % colors.length]);
});
Run Code Online (Sandbox Code Playgroud)

对于随机颜色,您可以使用:

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());
});
Run Code Online (Sandbox Code Playgroud)

演示:

http://jsbin.com/eqoyi4