单击时JavaScript按钮样式更改 [英] JavaScript Button Style change on click

查看:96
本文介绍了单击时JavaScript按钮样式更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将这段JavaScript放在一起,但由于我是新手,我正在努力解决这些问题。我想要做的是当点击一个按钮时,它将改变背景颜色的不透明度。下面的代码执行此操作,但现在我希望当我再次单击它时按钮恢复到正常状态。

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


正常状态:background =rgba(255,0,0,0.8);按下状态:
background =rgba(255,0,0,0.6);

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


推荐答案

我会使用CSS类:

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

并将您的功能更改为:

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

或者如果你只想使用JavaScript

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

更新(查看评论:如果使用2个按钮):

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

这篇关于单击时JavaScript按钮样式更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆