改变div的背景颜色

change background color of div(改变div的背景颜色)

本文介绍了改变div的背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这很简单,我搜索了但找不到确切的答案.

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

我想要做的就是有一个 div,当你点击一个链接时它会改变颜色.我想要大约 3 或 4 种颜色选择.我该怎么做?

All I want to do is have a div that will change color when you click a link. I want to have about 3 or 4 color choices. How do I do it?

谢谢!

推荐答案

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:

<div id="target"></div>
<button class="change-color" data-color="red">Red</button>
<button class="change-color" data-color="#000">Black</button>
<button class="change-color" data-color="rgb(0,0,255)">Blue</button>

<小时>

请注意,如果您希望所有颜色转换器都是同一元素的子元素,您可以使用事件委托并将前面的代码简化为


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:

<div id="target"></div>
<div id="color-changers">
    <button data-color="red">Red</button>
    <button data-color="#000">Black</button>
    <button data-color="rgb(0,0,255)">Blue</button>
</div>

演示:http://jsfiddle.net/jnAem/1/

这篇关于改变div的背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:改变div的背景颜色

基础教程推荐