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

Categories

0 votes
442 views
in Technique[技术] by (71.8m points)

css - Apply different background color using jquery

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

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

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...