javascript 使用jQuery按下后如何保持按钮处于活动状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13423782/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:43:55  来源:igfitidea点击:

How to keep button active after press with jQuery

javascriptjqueryhtmlcss

提问by pri0ritize

I've seen some very similar questions floating around but haven't been able to find the answer I'm looking for. I've already determined a work-around but would like to know the proper way to perform the task.

我看到了一些非常相似的问题,但一直无法找到我正在寻找的答案。我已经确定了一个变通方法,但想知道执行任务的正确方法。

What I desire is to click the button and have the active state stay persistent. The next click will toggle the state and that is desired. What I really need to know is how to address the uiButton:active state.

我想要的是单击按钮并使活动状态保持持久。下一次单击将切换状态,这是所需的。我真正需要知道的是如何解决 uiButton:active 状态。

HTML:

HTML:

<input type='button' class='uiButton' id='testbutton' value='testValue'>

CSS:

CSS:

.uiButton{
    background-color: red;
}

.uiButton:active{
    background-color:blue;
}

Javascript/jQuery:

Javascript/jQuery:

$('.uiButton').click(function() {
    $(this).toggleClass(//active state);
});

回答by Zoltan Toth

You should create an active class

您应该创建一个活动类

CSS

CSS

.uiButton:active, .active {
    background-color:blue;
}

JS

JS

$('.uiButton').click(function() {
    $(this).toggleClass("active");
});

回答by zzzzBov

:activeis a css pseudo-class. You want .activewhich is the classthat's being added to the element.

:active是一个 css伪类。你希望.active它是多数民众赞成在加入元素。

回答by EibergDK

You want the button to keep the active class after it's clicked? (not sure if you want to allow to be untoggled (red) again?).. Anyways...

您希望按钮在单击后保持活动类吗?(不确定是否要允许再次取消切换(红色)?).. 无论如何......

CSS:

CSS:

.uiButton {
   background-color: red;
}

.uiButton-active, .uiButton:hover {
   background-color: blue;
}

Then....:

然后....:

$('.uiButton').unbind('click').click(function() {
  $(this).attr('class', 'uiButton-active');
});

回答by David

You can't trigger a css pseudo selector like :active. The only option I know ist to simulate this

你不能触发像 .css 这样的 css 伪选择器:active。我知道的唯一选择是模拟这个

.uiButtonActive {
    background-color:blue;
}

Check out the working JSFIDDLE DEMO

查看正在运行的JSFIDDLE 演示