many divs with same class - different background

2019-08-28 02:30发布

问题:

so i have many divs with same class on the same page. i would like to add different backgrounds for each of them on my own choise(having 5-6 random backgrounds)

i found this code on the internet. but it chooses the same random color for all the divs.

 <script type="text/javascript">

/***********************************************
* Random Content Colors script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

//specify list of random background colors to apply to CSS class "randomcolor"
//For each entry, you can optionally specify a text and link color via the syntax:
// "BackgroundColor:TextColor" OR "BackgroundColor:TextColor:LinkColor"
var randombgcolors=["green:white:yellow", "#DDF4FF", "#FFFF97", "#CFFF9F"]

var rbcssrule=""
var randomnum=Math.floor(Math.random()*randombgcolors.length)
if (randombgcolors[randomnum].indexOf(":")!=-1){
rbcssrule="background-color: "+randombgcolors[randomnum].split(":")[0]+";"
rbcssrule+="color: "+randombgcolors[randomnum].split(":")[1]+";"
}
else
rbcssrule="background-color: "+randombgcolors[randomnum]+";"

document.write('<style type="text/css">\n')
document.write('.randomcolor{'+rbcssrule+'}\n')
if (randombgcolors[randomnum].split(":").length==3) //if link color specified
document.write('.randomcolor a{color:'+randombgcolors[randomnum].split(":")[2]+';}\n')
document.write('<\/style>')

</script>

回答1:

It looks like that code is setting its randomly chosen color to just one class: randomcolor. Assuming that all of your divs have that same class, they will all get that random color.

EDIT:

Check this JSFiddle I made, it should get you what you are looking for:

http://jsfiddle.net/VXG36/1/

HTML:

<div class="random">Div 1</div>
<div class="random">Div 2</div>
<div class="random">Div 3</div>

JQuery:

$(document).ready(function() {
    var randomColors = ["green","yellow","red","blue","orange","pink","cyan"];
    $(".random").each(function(index) {
        var len = randomColors.length;
        var randomNum = Math.floor(Math.random()*len);
        $(this).css("backgroundColor",randomColors[randomNum]);
        //Removes color from array so it can't be used again
        randomColors.splice(randomNum, 1);
    });
});


回答2:

My understanding is that your randomnum will always be 4. When it hits your "green:white:yellow" collection it will always split into randombgcolors[randomnum].split(":")[0] which is green, and randombgcolors[randomnum].split(":")[1] which is always white. Maybe when you hit randomnum as one you need a nother randomizer to pick between 0 and 2 to get your random green:white:yellow color.