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

Changing background-color of a button using 1 javascript

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

<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 更改每个按钮的颜色?

<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)"
    }
}

试试这个:-

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)"
    }
}
<input type="button" id="button" value = "button" onclick="setColor(this.id);"/>

您的脚本中存在 space 问题,我删除了脚本中 rgb 颜色的 spaces,它工作正常

 <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>