我不明白为什么这不起作用。它说backgroundColor是未定义的。我试图让它在点击时改变颜色并且点击工作但它不会改变颜色。我认为其他所有工作减去那个,但希望有人在这里可以帮助我。或者,如果您对如何改进它有任何建议,那就太棒了。
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>
答案 0 :(得分:2)
设置event.target
时应为backgroundColor
。
像这样:(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>
答案 1 :(得分:0)
您需要使用this
来获取事件发生的元素。
function changeColor(event) {
console.log("I work");
this.style.backgroundColor = randomColor();
}