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

Changing background-color of a button using 1 javascript

本文关键字:背景 颜色 按钮 1个 javascript 使用      更新时间:2024-01-29

我想更改按钮的背景色。这是我迄今为止的代码:

<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);"/>

您的脚本中存在空间问题,我在脚本中删除了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>