我不明白爲什麼這不起作用。它說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>
'event'不具有的樣式屬性。 –