使用dispatchEvent获得焦点事件

发布于 2024-11-18 08:46:13 字数 529 浏览 5 评论 0原文

当我在输入框上使用 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

When I trigger a focus event with dispatchEvent on an input box, its onfocus is called, but on the UI the input box is not focused.
Is there any reason for this behavior?

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);

On the other hand this works as expected.

var test = document.getElementById("test");
test.focus();

The reason i'm investigating this is that I use ZeptoJS to trigger events and it uses dispatchEvent.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

花想c 2024-11-25 08:46:13

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

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

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

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

test.onfocus = function(event) {
  console.log('focused');
  if( ! test.hasFocus() ) {
    test.focus();
  }
}

The element you fire an event on does not have to be listening for that event, since potentially, the parent element may also be listening for that event.

Note that manually firing an event does not generate the default action associated with that event. For example, manually firing a focus event does not cause the element to receive focus (you must use its focus() method for that), manually firing a submit event does not submit a form (use the submit() method), manually firing a key event does not cause that letter to appear in a focused text input, and manually firing a click event on a link does not cause the link to be activated, etc. In the case of UI events, this is important for security reasons, as it prevents scripts from simulating user actions that interact with the browser itself.

Also note that you should use fireEvent(), if you are working on IE. Also, the main difference between the dispatchEvent and fireEvent methods is that the dispatchEvent method invokes the default action of the event, the fireEvent method does not.

so for the solution please try this

test.onfocus = function(event) {
  console.log('focused');
  if( ! test.hasFocus() ) {
    test.focus();
  }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文