从元素中移除 :active 伪类

16
我希望能够告诉一个元素它不再处于:active状态,以便CSS规则不再适用。有没有办法在JavaScript中实现这一点?
4个回答

11

可能的解决方案:

1)使用类:

JS:

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

CSS:

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

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

编辑 : 显然,这只在Firefox上起作用。

JS :

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

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

HTML:

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

JS :

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

2
这是一种通过重置DOM元素来实现的技巧。
function resetElement(e){
    var $e = $(e);
    var $original = $e.clone();
    $e.replaceWith($original);
}

然后使用以下代码进行调用:
resetElement(document.activeElement);

1
测试通过。 这似乎是使用JS粗暴地移除:active的最佳答案。 - Tonis F. Piip
1
请注意,如果元素附加了任何事件(如onclick),它们将会丢失,您需要在克隆后重新附加它们。 - Mike Keskinov

1
对于jQuery用户:
JS:

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

HTML:

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

0

使用document.activeElement

document.activeElement = null;

或者

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

2
这是为了检测:focus状态,而不是:active状态。 - Tim Nguyen
1
document.activeElement只读的。因此,将null赋值给它将没有任何效果。 - nishanthshanmugham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接