BackgroundColor未定义
问题描述:
我不明白为什么这不起作用。它说backgroundColor是未定义的。我试图让它改变颜色,当点击和点击作品,但它不会改变颜色。我认为一切工作减去,但希望有人在这里可以帮助我。或者,如果您有任何关于如何改进它的建议,那将会很棒。 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>
答
您需要使用this
获得该事件发生的元素。
function changeColor(event) {
console.log("I work");
this.style.backgroundColor = randomColor();
}
答
应该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>
'event'不具有的样式属性。 –