DIV 通过事件处理程序"click"更改颜色



我想创建一个事件,在该事件中,单击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;
}

这里有一把小提琴:http://jsfiddle.net/r2vfa2s4/

有两件事。

将第一行更改为:

var squareRef = document.getElementsByClassName("square");

调用randomColor()时删除引号。即:

event.target.style.backgroundColor = randomColor();

您在两行上犯了错误

您必须更改特定div的颜色,而不是容器div,所以请更改此

var squareRef = document.getElementById("container");

var squareRef=document.getElementsByClassName("square");

您以错误的方式调用函数:

更改此行

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;
}
.square {
        width: 100px;
        height: 100px;
        background-color: #000000;
        margin: 5px;
    }
<div id="container">
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="square"></div>
</div>

对于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部分负责处理此问题;)

相关内容

  • 没有找到相关文章

最新更新