我想创建一个事件,单击 DIV 后它们会更改为随机颜色。我相当有信心这是一般设置,但我只是忽略了一些小错误......
HTML
<style>
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
</style>
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
JAVASCRIPT
var squareRef = document.getElementById("container");
for(var i = 0; i < squareRef.length; i++) {
squareRef[i].addEventListener("click", changeColor);
}
function changeColor(event) {
event.target.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;
}
最佳答案
这是一个 fiddle :http://jsfiddle.net/r2vfa2s4/
有两件事。
将第一行更改为:
var squareRef = document.getElementsByClassName("square");
调用 randomColor() 时删除引号。即:
event.target.style.backgroundColor = randomColor();
关于javascript - DIV 使用事件处理程序更改颜色 "click",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26901717/