Javascript 在pageload中将相同的随机颜色分配给多个div

Javascript 在pageload中将相同的随机颜色分配给多个div,javascript,html,css,Javascript,Html,Css,我希望图标的背景随机化为与文本相同的颜色。你可以看到有四种颜色可供选择,所以它不是完全随机的,而是在这四种颜色之间随机选择的 这就是我到目前为止所做的: HTML: JS: 我认为下面的链接可能是一个答案,但我似乎无法理解: 这里的代码有很多问题,让我们来讨论一下 一,。永远不要创建像这个新的Arraysilver、BAF3C3、c3baf3、red这样的javascript数组。它过于冗长,没有任何好处。使用数组文字语法,如下所示:[silver、BAF3C3、c3baf3、red] 二,。通

我希望图标的背景随机化为与文本相同的颜色。你可以看到有四种颜色可供选择,所以它不是完全随机的,而是在这四种颜色之间随机选择的

这就是我到目前为止所做的:

HTML: JS: 我认为下面的链接可能是一个答案,但我似乎无法理解:

这里的代码有很多问题,让我们来讨论一下

一,。永远不要创建像这个新的Arraysilver、BAF3C3、c3baf3、red这样的javascript数组。它过于冗长,没有任何好处。使用数组文字语法,如下所示:[silver、BAF3C3、c3baf3、red]

二,。通过添加一个变量,该功能非常简单:

function randomTextAndIconColor(){
    var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
    document.querySelector('.monobg').style.backgroundColor = color;
    document.querySelector('body').style.color = color;
}
您可以这样做:

HTML: 纯JS: 纯JS供参考

jQuery: jQuery作为参考

说明:
在样式表中定义不同的css类,每种颜色一个,然后创建一个JS数组,其中包含每个css类作为值,并且您只将其中一个随机分配给document.ready.

上的body元素。

您必须知道复制/粘贴不是正确的学习方法……如果您已经更改了某些文本的颜色,并且您了解执行该操作的代码,则在图标上应用相同的操作不会有问题
.monobg  {
    background-color: red;
    padding:10px;
    width:60px;
}
function random_imglink(){
    var myimages=new Array();
    //specify random images below. You can have as many as you wish
    myimages[1]="This is text1.";
    myimages[2]="This is text2.";
    myimages[3]="This is text3.";
    myimages[4]="This is text4.";
    myimages[5]="This is text5.";
    myimages[6]="This is text6.";

    var ry=Math.floor(Math.random()*myimages.length);
    if (ry==0)
        ry=1;
    document.write('<p>'+myimages[ry]+'</p>');
}
document.addEventHandler("ready", function() {
    random_imglink();
    var bgcolorlist = new Array("silver", "#BAF3C3", "#c3baf3", "red");
    document.body.style.color=bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
});
function randomTextAndIconColor(){
    var color = bgcolorlist[Math.floor(Math.random()*bgcolorlist.length)];
    document.querySelector('.monobg').style.backgroundColor = color;
    document.querySelector('body').style.color = color;
}
<div class="monobg">
    <img src="http://chloesilver.ca/mono1.png" />
</div>
<p>Some text</p>
.blue {
    color: blue;
}
.monobg {
    background-color: red;
    padding:10px;
    width:60px;
}
.blue .monobg {
    background: blue;
}
.red {
    color: red;
}
.red .monobg {
    background: red;
}
.green {
    color: green;
}
.green .monobg {
    background: green;
}
function setColor() {
    var colors = [" red", " green", " blue"],
        css = colors[Math.floor(Math.random() * colors.length)];
    document.querySelector("body").className = document.querySelector("body").className + css;
}
window.addEventListener("load", setColor);
jQuery(function($) {
    $(document).ready(function() {
        var colors = ["red", "green", "blue"],
            css = colors[Math.floor(Math.random() * colors.length)];
        $("body").addClass(css);
    });
});