javascript - dispatchEvent 'mouseover' 不工作

标签 javascript events

我有以下代码 http://jsfiddle.net/yc7sj3pt/2/

document.getElementById('obj_one').addEventListener('mouseover', function(){
    var e = document.createEvent('HTMLEvents');
    e.initEvent('mouseover', true, false);

    document.getElementById('obj_two').dispatchEvent(e);
    console.log('hover');
}, false);

当我在 #obj_onemouseover 时,我试图让 #obj_two 对悬停使用react(因此变为红色),但它不工作。我做错了什么?

最佳答案

根据 this answer ,你不能:

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.

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

推荐的方法是在 mouseovermouseout 事件上添加和删除一个类,我已经在这个 jsfiddle 中完成了。 .

关于javascript - dispatchEvent 'mouseover' 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32381243/

相关文章:

javascript - 删除包含特定字符串的 <p>

javascript - 如何使用特定值将 json 数组转换为 javascript 数组

javascript - 尝试使用扩展运算符创建数组的副本,但有些数组是如何变异的

javascript - 字符串连接不起作用,抛出错误

javascript - 如何在打印完成或取消时执行一些 JavaScript

events - GWT 中的 Fire ResizeEvent (Google Web Toolkit)

javascript - 如何将事件对象传递给事件处理程序

C# 如何在按住鼠标按钮时循环

javascript - 如何在 Javascript XPath 中为 KML 文件生成命名空间

.net - WPF。 MVVM。使用事件是不好的口气吗?