0

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 or 4 color choices. How do I do it?

Thanks!

4

2 回答 2

0

这是一个快速的解决方案

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function changeColor(color){
    var div = document.getElementById('box');
    div.style.backgroundColor = color;  
}
</script>
</head>

<body onload="changeColor('green')">

<div id="box" style="width:200px; height:200px;"></div>

<a href="#" onclick="changeColor('yellow')">Yellow</a>|

<a href="#" onclick="changeColor('green')">Green</a>|

<a href="#" onclick="changeColor('blue')">Blue</a>|

<a href="#" onclick="changeColor('white')">White</a>
</body>
</html>
于 2013-08-19T00:56:44.130 回答
0

演示: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>

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

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/

于 2013-08-19T01:00:57.123 回答