Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 如何为不同的div替换样式(背景色)?_Jquery_Css_Jquery Selectors - Fatal编程技术网

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

Jquery 如何为不同的div替换样式(背景色)?,jquery,css,jquery-selectors,Jquery,Css,Jquery Selectors,如果我有这样的HTML,如何使用id=“container”交替(偶数和奇数)为div中的div替换样式(使用jquery的背景色) <div id="container"> <div></div> <div></div> <div></div> <div></div> ... </div> 但是所有的[div]应该有不同的颜色…?没有一个div应该

如果我有这样的HTML,如何使用id=“container”交替(偶数和奇数)为div中的div替换样式(使用jquery的背景色)

<div id="container">
   <div></div> 
   <div></div>
   <div></div>
   <div></div>
...
</div>
但是所有的[div]应该有不同的颜色…?没有一个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());
});
演示:

试试这个:

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());
});
演示:


这在Firefox中对我很有用。你没有试过附带的演示吗?这对我在Firefox中很有用。你没有试过附带的演示吗?