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
How to trigger CSS "hover state" using Javascript?
提问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 :focus
instead of hover, you can use:
如果您可以接受 using:focus
而不是悬停,则可以使用:
var links = document.getElementsByTagName('a');
links[0].focus();
Or
或者
var linkToFocus = document.getElementById('link');
linkToFocus.focus();
This approach, obviously, requires adapting your CSS to include the a:focus
style:
显然,这种方法需要调整您的 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 样式复制到另一个类中,然后在希望它们永久更改时将该类名添加到元素中。伪类是“伪”是有原因的。