2013-06-25 30 views
0

我想使用JavaScript將#Content.backgroundColor更改爲elem.backgroundColor使用JavaScript將Div.backgroundColor更改爲Element.backgroundColor

下面是HTML代碼:

<button class="red" onClick="changeColor(this);">Btn1</button> 
<button class="blue" onClick="changeColor(this);">Btn2</button> 
<button class="green" onClick="changeColor(this);">Btn3</button> 
<div id="Content"></div> 

這裏是CSS代碼:

.red { 
    background-color: #ff0000; 
} 
.blue { 
    background-color: #0000ff; 
} 
.green { 
    background-color: #00ff00; 
} 
#Content { 
    background-color: #000; 
    width: 150px; 
    height: 150px; 
} 

JS代碼是在這裏:(我的問題是在這裏)

function changeColor(elem){ 
document.getElementById("Content").style.backgroundColor = elem.style.backgroundColor;  
} 

DEMO in JsFiddle.

我在做什麼錯?

回答

3

style屬性映射到style屬性上,而不是通過運行級聯計算的CSS屬性的值。您需要檢查the computed style

+3

像這樣:http://jsfiddle.net/QZcSF/3/。 – VisioN