change background color of div

后端 未结 2 2035
一生所求
一生所求 2021-01-26 13:29

this is so simple and I searched but couldn\'t find the exact answer.

All I want to do is have a div that will change color when you click a link. I want to have about 3

2条回答
  •  长情又很酷
    2021-01-26 13:54

    Demo: http://jsfiddle.net/jnAem/

    JS:

    var els = document.getElementsByClassName('change-color'),
        target = document.getElementById('target'),
        changeColor = function(){
            target.style.backgroundColor = this.getAttribute('data-color');
        };
    for(var i=els.length-1; i>=0; --i){
        els[i].onclick = changeColor;
    }
    

    HTML:


    Note that if you want all color changers to be children of same element, you can use event delegation and reduce the previous code to

    JS:

    document.getElementById('color-changers').onclick = function(e) {
        var color = (e ? e.target : window.event.srcElement).getAttribute('data-color');
        if(color){
            target.style.backgroundColor = color;
        }
    }
    

    HTML:

    Demo: http://jsfiddle.net/jnAem/1/

提交回复
热议问题