我想创建一个单击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>
JAVSCRIPT
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;
}
答案 0 :(得分:0)
这是一个小提琴:http://jsfiddle.net/r2vfa2s4/
两件事。
将第一行更改为:
var squareRef = document.getElementsByClassName("square");
调用randomColor()时删除引号。即:
event.target.style.backgroundColor = randomColor();
答案 1 :(得分:0)
你在两条线上犯了错误
你必须更改特定div的颜色而不是容器div,所以请更改此
var squareRef = document.getElementById("container");
要
var squareRef = document.getElementsByClassName(&#34; square&#34;);
和
你以错误的方式调用函数:
更改此行
event.target.style.backgroundColor = "randomColor()";
到
event.target.style.backgroundColor = randomColor();
试试这个
var squareRef = document.getElementsByClassName("square");
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;
}
&#13;
.square {
width: 100px;
height: 100px;
background-color: #000000;
margin: 5px;
}
&#13;
<div id="container">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
&#13;
答案 2 :(得分:0)
对于JavaScript,这有效:
var ref = [].slice.call(document.getElementsByClassName("square"));
ref.forEach(function(v,k,a)
{
v.onclick = function()
{
var clr = Math.floor(Math.random() * 255);
this.style.backgroundColor = 'hsla('+clr+',100%,50%,1)';
};
});
顺便说一下: 循环通过从“getElementsByClassName”获取的nodeList,在尝试引用时产生错误,因为nodeList也包含非元素。
[].slice.call
部分负责处理;)