gpt4 book ai didi

javascript - 背景颜色未定义

转载 作者:行者123 更新时间:2023-12-02 16:14:38 25 4
gpt4 key购买 nike

我不明白为什么这不起作用。它说背景颜色未定义。我试图让它在单击时改变颜色,并且单击有效,但它不会改变颜色。我认为除此之外,其他一切都有效,但希望这里有人可以帮助我。或者如果您对如何改进它有任何建议,那就太好了。

var squares=document.getElementsByClassName('squares');

for(var i = 0; i < squares.length; i++) {
squares[0].addEventListener("click", changeColor);
}

function changeColor(event) {
console.log("I work");
event.style.backgroundColor=randomColor();

}

//the code below is fine if you're trying to debug it you've gone too far
function randomColor() {

var randomRed = Math.floor(Math.random() * 255);
var randomGreen = Math.floor(Math.random() * 255);
var randomBlue = Math.floor(Math.random() * 255);
//create the string that is the ‘random color’
var randomColor = "rgb("+randomRed+","+randomGreen+","+randomBlue+")";

return randomColor;
}
<!DOCTYPE html>
<html>
<head>
<title>FIX IT.</title>
<style>
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
</style>
</head>
<body>

<div id="container">
<div class="square" onclick="changeColor(event)"></div>
<div class="square" onclick="changeColor(event)"></div>
<div class="square" onclick="changeColor(event)"></div>
<div class="square" onclick="changeColor(event)"></div>
</div>

<script src="main.js"></script>
</body>
</html>

最佳答案

当您设置backgroundColor时,它应该是event.target

像这样:(event.target).style.backgroundColor=randomColor();

event.target 将引用被单击的 div 元素。这样您就可以添加任何样式。

因此,您更改后的代码如下所示:

var squares=document.getElementsByClassName('squares');

for(var i = 0; i < squares.length; i++) {
squares[0].addEventListener("click", changeColor);
}

function changeColor(event) {
console.log("I work");
(event.target).style.backgroundColor=randomColor(); // Observe the difference here

}

//the code below is fine if you're trying to debug it you've gone too far
function randomColor() {

var randomRed = Math.floor(Math.random() * 255);
var randomGreen = Math.floor(Math.random() * 255);
var randomBlue = Math.floor(Math.random() * 255);
//create the string that is the ‘random color’
var randomColor = "rgb("+randomRed+","+randomGreen+","+randomBlue+")";

return randomColor;
}
<!DOCTYPE html>
<html>
<head>
<title>FIX IT.</title>
<style>
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
</style>
</head>
<body>

<div id="container">
<div class="square" onclick="changeColor(event)"></div>
<div class="square" onclick="changeColor(event)"></div>
<div class="square" onclick="changeColor(event)"></div>
<div class="square" onclick="changeColor(event)"></div>
</div>

<script src="main.js"></script>
</body>
</html>

关于javascript - 背景颜色未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29804002/

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