简体   繁体   中英

Changing background-color of a button using 1 javascript

I want to change the background-color of my button. This is my code so far:

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

This works with one button. If I have multiple buttons it only change the first button color. How can I change the color of every button with this 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)"
    }
}

Try This:-

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

There is space issue in your script, I removed spaces in rgb colors in script and it is working fine

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM