javascript - 单击按钮时更改 Element.attr

标签 javascript jquery html

我的问题很像 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;    
);

DEMO in JsFiddle.

<小时/>

附:

正如我上面提到的,请不要提出类似的建议:

// 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;
    }
}

Demo

关于javascript - 单击按钮时更改 Element.attr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17299915/

相关文章:

javascript - 将分页文章链接到侧边栏

javascript - 如何根据输入文本搜索显示所有嵌套的列表元素?

javascript - 从外部源解析 JSON

javascript - 将 javascript 代码与 html 代码一起使用

javascript - 三 Angular 形的 WebGL 代码,但三 Angular 形不会显示

javascript - 每次滚动页面时如何阻止 Jquery countTo 刷新

javascript - Vanilla JS - 可以在子元素上添加/删除类,但都处于事件状态

javascript - jquery自动完成json值

jquery - 如何使用 Jquery 在 div 中找到 div 并添加 css

html - 在开始时声明文档类型更改标题的外观