2016-09-26 64 views
0

我有10个按钮,当点击其中一个按钮时,按钮应该将自己的背景颜色更改为#B2DD28。 -这个怎么做?按钮:Onclick更改自己bgcolor

<button type="button" onClick="">time:</button> 
<button type="button" onClick="">length:</button> 
<button type="button" onClick="">position:</button> 

- 这是可能的JavaScript?要做到这一点

回答

0

一种方法是创建一个CSS样式类

.myColor {背景颜色:#B2DD28; }

并将该类添加到每个按钮的单击事件上。喜欢的东西

$(本).addClass(myColor)

+0

需要多一点代码 - 类似于在您的示例中缺少。 – Heiko

2

您可以将此按钮itsef内使用..

<button type="button" onClick="this.style.background = 'red'">time:</button> 
0

请看一看这个示例中,我做它用纯Javascript编写而不是Jquery。

<button type="button" onClick="changeColor(this)">time:</button> 
 
<button type="button" onClick="changeDynamicColor(this, 'blue')">length:</button> 
 
<button type="button" onClick="changeDynamicColor(this, 'green')">position:</button> 
 

 

 
<script> 
 

 
function changeColor(e){ 
 

 
\t e.style.backgroundColor = "#B2DD28"; 
 
    
 
} 
 

 
function changeDynamicColor(e, color){ 
 

 
\t e.style.backgroundColor = color; 
 
    
 
} 
 

 

 
</script>

0

Here's相对琐碎的事件无关与自我意识不到替代的方式来做到这一点,如果你愿意......这可能是更好的使用恰当的事件处理程序注册模型由JavaScript提供(addEventListener)或像JQuery这样的框架。 :)

function derp() { 
 
    document.activeElement.style.backgroundColor = '#B2DD28'; 
 
}
<button type="button" onclick="derp()">time:</button> 
 
<button type="button" onclick="derp()">length:</button> 
 
<button type="button" onclick="derp()">position:</button>

只需点击“运行代码片断”上面,然后点击按钮,看到他们打开#B2DD28荫的绿色。 :)