使用jquery应用不同的背景颜色 [英] Apply different background color using jquery

查看:102
本文介绍了使用jquery应用不同的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个父div中的子div的集合,子div是动态生成的,并且都有相同的类名。



我的问题是如何申请使用jquery的每个子div的不同背景颜色
以下示例代码

 < div id =someid> 
< div class =bar> ...< / div>
< div class =bar> ...< / div>
< div class =bar> ...< / div>
< div class =bar> ...< / div>
< div class =bar> ...< / div>
< / div>

这里我想为每个子div应用不同的背景颜色(class =bars)

提前感谢。

解决方案



  var colors = [f0​​0,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)+')'
}
b $ b $('#someid .bar')。each(function(i){
$(this).css('background-color',randomColor());
}

演示:


http://jsbin.com/eqoyi4



I have a collection of child div's inside the parent div,the child div's are generated dynamically and all has the same class name.

My question is how to apply different background color for each child div using jquery sample code below

<div id="someid">
   <div class="bar">...</div>
   <div class="bar">...</div>
   <div class="bar">...</div>
   <div class="bar">...</div>
   <div class="bar">...</div>
</div>

Here i want to apply different background color for each child div( class="bars")

Thanks in advance.

解决方案

Something like this:

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

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

To produce random colors, you can use this:

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

Demo:

http://jsbin.com/eqoyi4

这篇关于使用jquery应用不同的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆