change background color of div

2020-05-08 06:32发布

问题:

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!

回答1:

Heres a quick solutions

<!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>


回答2:

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>

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