0

所以我在同一页面上有许多具有相同类的 div。我想根据自己的选择为每个人添加不同的背景(有 5-6 个随机背景)

我在互联网上找到了这段代码。但它为所有 div 选择相同的随机颜色。

 <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>
4

2 回答 2

3

看起来该代码将其随机选择的颜色设置为仅一类:randomcolor。假设您所有的 div 都具有相同的类,它们都将获得该随机颜色。

编辑:

检查我制作的这个 JSFiddle,它应该可以为您提供所需的内容:

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

HTML:

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

查询:

$(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);
    });
});
于 2013-08-15T18:44:24.083 回答
0

我的理解是,您的randomnum将始终为 4。当它到达您的 "green:white:yellow" 集合时,它将始终拆分为绿色的 randombgcolors[randomnum].split(":")[0] 和 randombgcolors[randomnum ].split(":")[1] 总是白色的。也许当您将randomnum设为 one 时,您需要另一个随机器在 0 和 2 之间进行选择,以获得随机的绿色:白色:黄色。

于 2013-08-15T19:03:03.593 回答