JavaScript Button Style change on click

2019-07-05 13:03发布

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

3条回答
孤傲高冷的网名
2楼-- · 2019-07-05 13:14

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)";
}
查看更多
倾城 Initia
3楼-- · 2019-07-05 13:20

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.

查看更多
来,给爷笑一个
4楼-- · 2019-07-05 13:23

@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 his answer doesn't show the HTML. Make sure to pass through the id element, not the name of the id.

查看更多
登录 后发表回答