简体   繁体   中英

Change background transparency of a button css javascript

I'm new here and I have a question that might be simple but I just couldn't find an answer after googling for a while.

I have some buttons in my browser game that are green with a white text. When I hover over them, I change the rgba with CSS and the green becomes more transparent:

#oneOfTheButtons:hover {
  background: rgba(76, 175, 80, 0.7) !important;
}

The white text stays the same. I also have some Javascript that changes the color if the player goes level up:

document.getElementById("oneOfTheButtons").style.background = "rgba(77, 173, 173, 1)";

Then the buttons are blue. But the problem is that a hover still makes them transparent green, but I want them to be a transparent blue. I have 20 more levels like that with different colors.

Is there any simple solution for this?

This could be done in many different ways, but you could do it with css variables like this:

 let green = true; function toggleColor() { if (green) { document.body.style.setProperty('--button-bg-color', '77, 173, 173'); } else { document.body.style.setProperty('--button-bg-color', '76, 175, 80'); } green = !green; } 
 :root { --button-bg-color: 76, 175, 80; } button { background: rgba(var(--button-bg-color), 1); } button:hover { background: rgba(var(--button-bg-color), 0.7); } 
 <button onclick="toggleColor()">Toggle hover color!</button> 

You could use the following css

.green:hover {
  background: rgba(76, 175, 80, 0.7);
}
.green {
  background: rgba(76, 175, 80, 1);
}
.blue {
  background: rgba(77, 173, 173, 1);
}
.blue:hover {
  background: rgba(77, 173, 173, 0.7);
}

And the following js

document.getElementById("oneOfTheButtons").className = "blue";

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