javascript 从元素中删除 :active 伪类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22016522/
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-27 22:13:22  来源:igfitidea点击:

Removing the :active pseudo-class from an element

javascriptpseudo-class

提问by basicallydan

I'd like to be able to tell an element that it is no longer :activeso that the CSS rules no longer apply. Is there any way to do this in JavaScript?

我希望能够告诉一个元素它不再是:active这样,CSS 规则不再适用。有没有办法在 JavaScript 中做到这一点?

回答by Tim Nguyen

Possible solutions :

可能的解决方案 :

1) Using classes :

1)使用类:

JS :

JS:

document.getElementById("element").classList.remove("hasactive");

CSS :

CSS :

#element.hasactive:active {
    background:blue;
}

2) Preventing default mousedown functionality (active state) :

2) 防止默认的鼠标按下功能(活动状态):

EDIT :Apparently, this only works on Firefox.

编辑:显然,这仅适用于 Firefox。

JS :

JS:

document.getElementById("element").onmousedown = function(event) {
    event.preventDefault();
}

3) Removing a style element with the css rule in it

3) 删除包含 css 规则的样式元素

HTML :

HTML :

<style id="activestyle">
#element:active {
/*Your code here*/
}
</style>

JS :

JS:

document.getElementById("activestyle").remove();

回答by Saitama

Here is a trick by resetting the DOM element.

这是重置 DOM 元素的一个技巧。

function resetElement(e){
    var $e = $(e);
    var $original = $e.clone();
    $e.replaceWith($original);
}

Then call it with:

然后调用它:

resetElement(document.activeElement);

回答by Oleg Shalaev

For jQuery users:
JS:

对于 jQuery 用户:
JS:

$(".btn").click( function () { $(this).blur(); } );

HTML:

HTML:

<button  type="button" class="btn btn-success">press me</button>

回答by Pinal

Use document.activeElement:

使用document.activeElement

document.activeElement = null;

OR

或者

document.activeElement && document.activeElement.blur();