使用1个javascript更改按钮的背景颜色

时间:2015-02-19 11:35:43

标签: javascript html button

我想更改按钮的背景颜色。 到目前为止,这是我的代码:

<script>
function setColor(btn) {
    var property = document.getElementById(btn);
    if (property.style.backgroundColor == "rgb(127, 255, 0)") {
        property.style.backgroundColor = "rgb(255, 0, 0)"  
    }
    else if(property.style.backgroundColor == "rgb(255, 0, 0)")
    {
        property.style.backgroundColor = ""
    }
    else {
        property.style.backgroundColor = "rgb(127, 255, 0)"
    }
}
</script>

<input type="button" id="button" value = "button" onclick="setColor('button')";/>

这适用于一个按钮。如果我有多个按钮,它只会更改第一个按钮颜色。如何使用此JavaScript更改每个按钮的颜色?

3 个答案:

答案 0 :(得分:3)

<input type="button" id="button" value = "button" onclick="setColor(this);"/>

JS:

function setColor(btn) {
    if (btn.style.backgroundColor == "rgb(127, 255, 0)") {
        btn.style.backgroundColor = "rgb(255, 0, 0)"  
    }
    else if(btn.style.backgroundColor == "rgb(255, 0, 0)")
    {
        btn.style.backgroundColor = ""
    }
    else {
        btn.style.backgroundColor = "rgb(127, 255, 0)"
    }
}

答案 1 :(得分:0)

试试这个: -

&#13;
&#13;
function setColor(btn) {
    var property = document.getElementById(btn);
    if (property.style.backgroundColor == "rgb(127, 255, 0)") {
        property.style.backgroundColor = "rgb(255, 0, 0)"  
    }
    else if(property.style.backgroundColor == "rgb(255, 0, 0)")
    {
        property.style.backgroundColor = ""
    }
    else {
        property.style.backgroundColor = "rgb(127, 255, 0)"
    }
}
&#13;
<input type="button" id="button" value = "button" onclick="setColor(this.id);"/>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

您的脚本中存在空间问题,我在脚本中删除了rgb颜色的空格并且工作正常

 <script>
   function setColor(btn) {
    var property = document.getElementById(btn);
    if (property.style.backgroundColor == "rgb(127,255,0)") {
       property.style.backgroundColor = "rgb(255,0,0)"  
     }
      else if(property.style.backgroundColor == "rgb(255,0,0)")
     {
         property.style.backgroundColor = ""
     }
     else {
         property.style.backgroundColor = "rgb(127,255,0)"
     }
  }
 </script>
相关问题