当我在输入框上使用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。
发布于 2011-07-05 13:13:03
触发事件的元素不必侦听该事件,因为父元素可能也在侦听该事件。
请注意,手动触发事件不会生成与该事件关联的默认操作。例如,手动激发focus事件不会导致元素接收焦点(必须使用其focus()方法),手动激发submit事件不会提交表单(使用submit()方法),手动激发键事件不会导致该字母出现在关注的文本输入中,手动激发链接上的单击事件不会激活链接,等等。对于UI事件,出于安全原因,这一点很重要,因为它阻止脚本模拟与浏览器本身交互的用户操作。
另请注意,如果您正在使用IE,则应使用fireEvent()。此外,dispatchEvent和fireEvent方法之间的主要区别是dispatchEvent方法调用事件的默认操作,而fireEvent方法不调用。
因此,要获得解决方案,请尝试以下内容
test.onfocus = function(event) {
console.log('focused');
if( ! test.hasFocus() ) {
test.focus();
}
}https://stackoverflow.com/questions/6577865
复制相似问题