2013-06-25 46 views
0

我的問題很像my last topic,但它不相同。單擊按鈕時更改Element.attr


我有幾個按鈕和CSS樣式。

HTML代碼是在這裏:

<button class="Btn red">Btn1</button> 
<button class="Btn blue">Btn2</button> 
<button class="Btn green">Btn3</button> 
<div id="Content"></div> 

和CSS代碼是在這裏:

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

我的問題是:

使用Javascript如何更改(#Content).backgroundcolor(Clicked_Btn).backgroundcolor

我曾嘗試下面JS命令,我覺得它有很多的問題:

$(".Btn").click(function(){ 
document.getElementById("Content").style.backgroundColor = getComputedStyle(this).backgroundColor;  
); 

DEMO in JsFiddle.


PS:

正如我上面提到請不要建議例如:

// HTML 

<button class="Btn red" onClick="changeColor(this);">Btn1</button> 
... 

//JavaScript 

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

我不想在HTML按鈕標籤內使用onClick("function();")

任何幫助都會很棒。

回答

4

純JavaScript(jQuery的不依賴):

var buttons = document.getElementsByTagName("button"); 
for(var i=0; i<buttons.length; i++){ 
    buttons[i].onclick = function(){ 
     document.getElementById("Content").style.backgroundColor = getComputedStyle(this).backgroundColor; 
    } 
} 

Demo

3

如果您使用的是$(「.Btn」),請點擊您正在使用的jQuery。這意味着您可以簡化大量後續行。

$(".Btn").click(function(){ 
    $("#Content").css('background-color',$(this).css('background-color')); 
}); 

,這裏是你的提琴編輯:DEMO