不同的div随机显示颜色

8

我有三个div

<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<button>Enter</button>

我希望用JavaScript控制CSS,为它设置随机颜色。就像这样:

var randomColor = Math.ceil(Math.random() * 3);
var color = "";
//Accessing the divs
var box1 = document.querySelector("#box1");
var box2 = document.querySelector("#box2");
var box3 = document.querySelector("#box3");

//Event
var button = document.querySelector("button");
button.addEventListener("click", randomize, false);
button.style.cursor = "pointer";

function render(){
    box1.style.background = color;
    box2.style.background = color;
    box3.style.background = color;
}

function randomize(randomColor){
    switch(randomColor){
        case 1:
        color = "red";
        break;
        case 2:
        color = "blue";
        break;
        case 3:
        color = "green";
        break;
    }
render();
}

问题在于,每个div都给了我相同的颜色。有什么办法可以解决这个问题吗?如果可能的话,我想用纯JavaScript和CSS来实现,不要用jQuery。我还在学习JavaScript。谢谢。

1
randomColor 的定义放入 randomize 函数中。 - Teemu
5个回答

12

你可以使用类(class)而不是ID(id),并将代码简化为以下形式。

// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");
var button = document.querySelector("button");

button.addEventListener("click", function () {
  for (i = 0; i < boxes.length; i++) {
    // Pick a random color from the array 'colors'.
    boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
    boxes[i].style.width = '100px';
    boxes[i].style.height = '100px';
    boxes[i].style.display = 'inline-block';
  }
});

button.style.cursor = "pointer";
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<button>Enter</button>


在页面刷新/加载时随机更改颜色。

// You could easily add more colors to this array.
var colors = ['red', 'blue', 'green', 'teal', 'rosybrown', 'tan', 'plum', 'saddlebrown'];
var boxes = document.querySelectorAll(".box");

for (i = 0; i < boxes.length; i++) {
  // Pick a random color from the array 'colors'.
  boxes[i].style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
  boxes[i].style.width = '100px';
  boxes[i].style.height = '100px';
  boxes[i].style.display = 'inline-block';
}
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>


每次点击时,我不希望它有不同的颜色。我想在刷新页面时为每个div设置一个确切的颜色。谢谢你的建议。 - Dexter C. Caga-anan
@DexterC.Caga-anan - 所以您不想在单击事件上更改颜色?并且仅在页面刷新或加载时设置颜色? - Weafs.py
是的,那是我想做的另一件事。 - Dexter C. Caga-anan
@DexterC.Caga-anan - 我添加了另一个片段,可以在页面刷新或加载时随机化颜色。 - Weafs.py

2

这个怎么样?

http://jsfiddle.net/stackmanoz/vymmb10s/

CSS-

div[class^="box"]{
    width:100px;
    height:100px;
    border:1px solid;
    display:inline-block;
    }

jQuery-

var colors = ['red', 'blue', 'green', 'gray', 'black', 'yellow'];
$(function(){
     $("#btn").click(function() {
     $('div[class^="box"]').each(function(){
        var randomColor = Math.floor(Math.random() * colors.length)
        $(this).css('background-color', colors[randomColor])
                                  });
});
});

0

var r = Math.floor(Math.random()*255);
var g = Math.floor(Math.random()*255);
var b = Math.floor(Math.random()*255);
for (var i = 0; i <= 5; i++) {
var div = document.getElementsByClassName("div")[i].style.backgroundColor = "rgb("+r+","+g+","+b+")";
}
div {
width: 200px;
height:200px;
display: inline;
float: left;
margin: 15px;
background-color: red;
}
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>
<div class="div"></div>


如果您在代码中加入一些解释,那么您的答案将更可靠。 - Suraj Kumar

0

我对命名字符串颜色列表感到震惊,没有看到任何人使用十六进制。对于像我这样想要不同东西的人,这里有:

function randomInt(max=1, min=0){
    // scale random number from 0 to 1 to desired min and max
    return parseInt( Math.random() * (max - min) + min );
}
function twoPlaces(sNum=''){
    // make sure all strings have a length greater than 1
    //   eg: "f" => "0f"
    return sNum.length > 1 ? sNum : twoPlaces('0'+sNum);
}
function randomColor(){
    // make each color's hex string
    let r = twoPlaces( randomInt(255,0).toString(16) );
    let g = twoPlaces( randomInt(255,0).toString(16) );
    let b = twoPlaces( randomInt(255,0).toString(16) );
    // return hex color string
    return `#${r}${g}${b}`;
}
function updateColors(){
    // loop through all elements with class "random"
    document.querySelectorAll(".random").forEach( (el)=>{
        // set each element/'s color to a random hex
        el.setAttribute("style",`background-color:${ randomColor() }`);
    } );
}

// add function to randomizer
let randomizer = document.querySelector("#colorRandomizer");
randomizer.addEventListener("click",updateColors);
// initialize colors
randomizer.dispatchEvent( new Event("click") );
div {
    width: 100%;
    height: 100%;
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
}
.random{
    height: 100px;
}
<button id="colorRandomizer">Randomize</button>
<div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
    <div class="random"></div>
</div>


0
*

<html>
        <head>
            <style>
                div {
                    width: 100px;
                    height: 100px;
                    position: relative;
                    border: 1px solid black;
                    float: left;
                    margin: 5px;
                }
            </style>
        </head>
        <body>
            <div id="first"></div>
            <div id="second"></div>
            <div id="third"></div>
            <div id="fourth"></div>
        </body>
        <script>
            let colors = ['red', 'green', 'blue', 'yellow'];
            (function () {
                document.getElementById("first").style.backgroundColor = assignColor();
                document.getElementById("second").style.backgroundColor = assignColor();
                document.getElementById("third").style.backgroundColor = assignColor();
                document.getElementById("fourth").style.backgroundColor = assignColor();
            })();
            function assignColor() {
                let colorIndex = Math.floor(Math.random() * colors.length);
                let color = colors[colorIndex];
                colors.splice(colorIndex, 1);
                return color;
            }
        </script>
    </html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接