Javascript 如何使用Javascript触发CSS“悬停状态”?

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

How to trigger CSS "hover state" using Javascript?

javascripthtmlcssbrowser

提问by Pacerier

CSS's "hovered state" will trigger when the user hovers over an element:

CSS 的“悬停状态”将在用户悬停在元素上时触发:

<style>
.element{

}
.element:hover{
    background-color:red;
}
</style>

How can we set the element to "hovered state" using Javascript?

我们如何使用 Javascript 将元素设置为“悬停状态”?

Is it possible?

是否可以?

采纳答案by David says reinstate Monica

If you could accept using :focusinstead of hover, you can use:

如果您可以接受 using:focus而不是悬停,则可以使用:

var links = document.getElementsByTagName('a');
links[0].focus();

JS Fiddle demo.

JS小提琴演示

Or

或者

var linkToFocus = document.getElementById('link');
linkToFocus.focus();

JS Fiddle demo.

JS小提琴演示

This approach, obviously, requires adapting your CSS to include the a:focusstyle:

显然,这种方法需要调整您的 CSS 以包含a:focus样式:

a:link, a:visited {
    background-color: #fff;
}
a:hover, a:focus, a:active {
    background-color: #f00;
}

回答by Scott

You're probably better off duplicating the :hover styles into another class and then just adding that class name to the element when you want them to change permanently. Pseudo-classes are "pseudo" for a reason.

您最好将 :hover 样式复制到另一个类中,然后在希望它们永久更改时将该类名添加到元素中。伪类是“伪”是有原因的。