当我在输入框上使用 dispatchEvent
触发 focus
事件时,它的 onfocus
被调用,但在 UI 上输入框是不专注。
这种行为有什么原因吗?
var test = document.getElementById("test");
test.onfocus = function(event) {
console.log('focused');
}
var e = document.createEvent('Event');
e.initEvent("focus", true, true);
test.dispatchEvent(e);
另一方面,这按预期工作。
var test = document.getElementById("test");
test.focus();
我调查这个的原因是我使用 ZeptoJS 触发事件,它使用 dispatchEvent
。
最佳答案
触发事件的元素不必监听该事件,因为父元素也可能监听该事件。
请注意,手动触发事件不会生成与该事件关联的默认操作。例如,手动触发 focus
事件不会使元素获得焦点(您必须为此使用其 focus()
方法),手动触发 submit
事件不提交表单(使用 submit()
方法),手动触发按键事件不会导致该字母出现在聚焦文本输入中,手动触发点击事件在链接上不会导致链接被激活等。在 UI 事件的情况下,出于安全原因,这很重要,因为它可以防止脚本模拟与浏览器本身交互的用户操作。
另请注意,如果您使用的是 IE,则应使用 fireEvent()
。此外,dispatchEvent
和 fireEvent
方法之间的主要区别在于 dispatchEvent
方法调用事件的默认操作,即 fireEvent
方法没有。
所以对于解决方案,请尝试这个
test.onfocus = function(event) {
console.log('focused');
if( ! test.hasFocus() ) {
test.focus();
}
}
关于javascript - 使用 dispatchEvent 的焦点事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6577865/