【发布时间】:2015-04-19 03:57:29
【问题描述】:
我已经使用事件侦听器将其写出来,但它不起作用,即使单击它们,方块仍保持黑色。我发现了一些拼写错误,但我不确定我使用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;
}
【问题讨论】:
标签: javascript html event-handling dom-events onclicklistener