gpt4 book ai didi

javascript - 在 Javascript 中生成随机正方形的随机颜色

转载 作者:行者123 更新时间:2023-11-28 17:16:10 25 4
gpt4 key购买 nike

该按钮应该将随机方 block 的颜色更改为随机颜色。这是我的代码,我弄清楚了如何同时更改每个方 block 的随机颜色,但它应该一次只选择一个随机方 block 。可以请您看一下吗?评论会告诉你我的思维方式:

// Elements grabbed from the document
let square1 = document.getElementById('square1');
let square2 = document.getElementById('square2');
let square3 = document.getElementById('square3')
let button = document.getElementById('button');

//This picks a random number
const rgb = (num) => {
return Math.floor(Math.random() * num);
};

const changeColorOfaRandomSquareToRandom = () => {
//This I hope will pick a random square
let array = [square1, square2, square3];
let randomNumber = Math.floor[Math.random() * 3];

// I assign the value of the randomSquare function to a new variable
let squareRND = array[randomNumber];

//This picks a random color
let randomColor = 'rgb(' + rgb(255) + ',' + rgb(255) + ',' + rgb(255) + ')';
return squareRND.style.backgroundColor = randomColor();


}

button.onclick = changeColorOfaRandomSquareToRandom();
#square1{
background-color: lightpink;
width:200px;
height: 200px;
display: flex;
margin-top: 200px;
}


#square2{
background-color: lightblue;
width: 200px;
height: 200px;
display: flex;
margin-top: 200px;

}

#square3{
background-color: lightgreen;
width: 200px;
height: 200px;
display: flex;
margin-top: 200px;
}

#squares{
display: flex;
flex-wrap: wrap;
justify-content: center;
}

#button{
width: 75px;
height: 25px;
margin-top: 20px;
margin-left: 600px;

}
<html>
<head>
<link href="squares.css" type="text/css" rel="stylesheet"/>
</head>
<body>
<div id="squares">
<div id="square1" onclick="colorChange">
</div>
<div id="square2">
</div>
<div id="square3">
</div>
</div>
<button id="button">Click me</button>
<script src="square.js" ></script>
</body>
</html>

最佳答案

在你的let array = ['square1', 'square2', 'square3'];中,如果你直接传入变量而不是字符串,它应该可以工作。现在你正在做 'square1'.style.backgroundColor =

关于javascript - 在 Javascript 中生成随机正方形的随机颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53448993/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com