我已经使用事件监听器将其写出来,但它不起作用,并且即使单击它们,方 block 仍保持黑色。我发现了一些拼写错误,已修复,但我不确定使用 getElementsByClassName
是否正确。
html:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
</style>
</head>
<body>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script src="js/main.js"></script>
</body>
</html>
和 JavaScript:
var squares = document.getElementsByClassName('square');
for(var i = 0; i < squares.length; i++) {
squares[0].addEventListener("click", changeColor);
}
function changeColor(event) {
event.style.backgroundColor = randomColor();
}
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;
}
最佳答案
两个基本问题:
- 您的 for 循环有一个硬编码的
squares[0]
,而它应该是squares[i]
,因此您将处理程序多次绑定(bind)到第一个元素,并且不给其他人。 event
对象没有style
属性。使用this.style.backgroundColor
- 在处理程序中this
将引用单击的元素。或者使用event.target.style.backgroundColor
。
就像这样:
for(var i = 0; i < squares.length; i++) {
squares[i].addEventListener("click", changeColor);
}
function changeColor(event) {
this.style.backgroundColor = randomColor();
}
关于javascript - 当使用 JavaScript 单击方 block 时,如何使方 block 的颜色发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29725608/