简体   繁体   中英

JavaScript Button Style change on click

I have put together this piece of JavaScript, but I am struggling with the code as I'm a newbie. What I want to do is when a button is clicked it will change the background color opacity. The code below does this, but now I want the button to be reverted to the normal state when I click it again.

How can I do this? Thanks..

Normal state: background="rgba(255,0,0,0.8)"; Pressed state: background="rgba(255,0,0,0.6)";

function highlight(id) {
document.getElementById(id).style.background="rgba(255,0,0,0.6)";
}

I would use a CSS class:

.opacityClicked{
  background:rgba(255,0,0,0.8);
}
.opacityDefault{
  background:rgba(255,0,0,0.6);
}

And change your function to:

function highlight(id) {
    var element = document.getElementById(id);
    element.class = (element.class == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}

Or if you want to use only JavaScript

var isClicked = false;
function highlight(id) {
    isClicked = !isClicked;
    var element = document.getElementById(id);
    element.style.background = (isClicked  == true) ? "rgba(255,0,0,0.6)" : "rgba(255,0,0,0.8)";
}

Update( See comments: if you use 2 buttons ):

var buttonClicked = null;
function highlight(id) {
    if(buttonClicked != null)
    {
        buttonClicked.style.background = "rgba(255,0,0,0.8)";
    }

    buttonClicked  = document.getElementById(id);
    buttonClicked.style.background =  "rgba(255,0,0,0.6)";
}

You could do something really quick like this:

First, add a hidden input element to your page like so:

<input type="button" id="foobar" value="FooBar!" onclick="highlight('foobar')" style="background-color:rgba(255,0,0,0.8);" />

<input type="hidden" id="one_neg_one" value="1" />  <= hidden element

Next, put this in your highlight function:

function highlight(id) {
    var a = 7;
    var o = document.getElementById("one_neg_one");
    var newa = (a + (parseInt(o.value) * -1)) * 0.1;
    document.getElementById(id).style.background="rgba(255,0,0," + newa + ")";
    o.value = o.value * -1;
}

That should work, although I agree with a previous answer that you should use a css class for this.

@Ruben-J answer works fine. There is a syntax error though - you should instead use element.className rather than element.class.

https://developer.mozilla.org/en-US/docs/Web/API/Element/className

Below is an updated answer using the correct syntax:

function highlight(id) {
   var element = document.getElementById(id);
   element.className = (element.className == "opacityClicked") ? "opacityDefault" : "opacityClicked";
}

Also noticed that this answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.

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