2012-03-03 94 views
0

如何替换样式(背景颜色使用jQuery)的DIV中使用id =“容器”交替(偶数和奇数)DIV,如果我有HTML这样如何替换div divs的样式(背景颜色)?

<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"); 
表?

但所有的[的div]应该有不同的颜色...不派息应该具有相同的颜色..can任何一个可以帮助我..

回答

6

试试这个:

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

+0

不,这不是working..the颜色不显示 – 2012-03-03 14:38:05

+0

这适用于我在Firefox。你有没有尝试附加演示? – 2013-01-29 22:14:30