使用dispatchEvent聚焦事件

Vik*_*tor 5 javascript events focus javascript-events setfocus

当我在输入框上触发focus事件时dispatchEvent,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);
Run Code Online (Sandbox Code Playgroud)

另一方面,这可以按预期工作.

var test = document.getElementById("test");
test.focus();
Run Code Online (Sandbox Code Playgroud)

我正在调查的原因是我使用ZeptoJS来触发事件并使用它dispatchEvent.

Tal*_*han 7

您触发事件的元素不必侦听该事件,因为潜在地,父元素也可能侦听该事件。

请注意,手动触发事件不会生成与该事件关联的默认操作。例如,手动触发focus事件不会导致元素获得焦点(您必须focus()为此使用其方法),手动触发submit事件不会提交表单(使用该submit()方法),手动触发关键事件不会导致该字母出现在焦点文本输入中,并在链接上手动触发单击事件不会导致链接被激活等。在 UI 事件的情况下,出于安全原因,这很重要,因为它可以防止脚本模拟用户操作与浏览器本身交互。

另请注意fireEvent(),如果您使用的是 IE,则应使用。此外,dispatchEventfireEvent方法之间的主要区别在于dispatchEvent方法调用事件的默认操作,fireEvent方法不调用。

所以对于解决方案,请试试这个

test.onfocus = function(event) {
  console.log('focused');
  if( ! test.hasFocus() ) {
    test.focus();
  }
}
Run Code Online (Sandbox Code Playgroud)