如何在纯 JavaScript 中模拟鼠标悬停以激活 CSS“:hover"?

How do I simulate a mouseover in pure JavaScript that activates the CSS quot;:hoverquot;?(如何在纯 JavaScript 中模拟鼠标悬停以激活 CSS“:hover?)

本文介绍了如何在纯 JavaScript 中模拟鼠标悬停以激活 CSS“:hover"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在 Chrome 中寻找模拟 mouseover 的代码,但即使mouseover"侦听器被触发,CSShover"声明也从未设置!

I've been trying to find code to simulate mouseover in Chrome but even though the "mouseover" listener gets fired, the CSS "hover" declaration is never set!

我也尝试过:

//Called within mouseover listener
theElement.classList.add("hover");

但似乎没有任何东西将元素更改为其 hover 声明中声明的内容.

But nothing seems to change the element to what is declared in its hover declaration.

这可能吗?

推荐答案

你不能.这不是可信事件.

由用户代理生成的事件,无论是作为用户交互的结果,还是作为对 DOM 更改的直接结果,都受到用户代理的信任,其权限是脚本通过DocumentEvent.createEvent(Event") 方法,使用 Event.initEvent() 方法修改,或通过 EventTarget.dispatchEvent() 方法调度.可信事件的 isTrusted 属性值为 true,而非可信事件的 isTrusted 属性值为 false.

Events that are generated by the user agent, either as a result of user interaction, or as a direct result of changes to the DOM, are trusted by the user agent with privileges that are not afforded to events generated by script through the DocumentEvent.createEvent("Event") method, modified using the Event.initEvent() method, or dispatched via the EventTarget.dispatchEvent() method. The isTrusted attribute of trusted events has a value of true, while untrusted events have a isTrusted attribute value of false.

大多数不受信任的事件不应触发默认操作,点击或 DOMActivate 事件除外.

Most untrusted events should not trigger default actions, with the exception of click or DOMActivate events.

您必须手动添加一个类并在 mouseover/mouseout 事件中添加/删除它.

You have to add a class and add/remove that on the mouseover/mouseout events manually.

这篇关于如何在纯 JavaScript 中模拟鼠标悬停以激活 CSS“:hover"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何在纯 JavaScript 中模拟鼠标悬停以激活 CSS“:hover"?

基础教程推荐