2013-06-25 44 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