Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
436 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...