我已经使用事件侦听器写出了它,但它不起作用,即使点击它们也仍然黑色。我发现了一些我修正的拼写错误,但我不确定我是否正确使用getElementsByClassName。当我们点击Javascript时,如何改变方块的颜色?
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;
}
如果某个元素有多个类,则您的自定义'getElementsByClass()'函数是否可以工作? – nnnnnn
让我解决这个问题。 – PHPglue