我的问题很像 my last topic ,但并不相同。
<小时/>我有几个按钮并由 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;
);
<小时/>
附:
正如我上面提到的,请不要提出类似的建议:
// 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();")
。
任何帮助都会很棒。
最佳答案
纯 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;
}
}
关于javascript - 单击按钮时更改 Element.attr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17299915/