简体   繁体   English

确定什么触发了焦点事件?

[英]Determine what triggered focus event?

I need to determine what caused a focus event.我需要确定导致焦点事件的原因。

Ideally, I want to differentiate between a click, a tab/keyboard input, and a manual (via code) trigger.理想情况下,我想区分单击、选项卡/键盘输入和手动(通过代码)触发器。

How can I do this?我怎样才能做到这一点?

I'm looking at the event object, but I'm not seeing anything too useful.我正在查看事件 object,但我没有看到任何太有用的东西。

If the focus comes from a $x.focus() call, then the event won't have an originalEvent property because there was no event from the browser so:如果焦点来自$x.focus()调用,则该事件将没有originalEvent属性,因为没有来自浏览器的事件,所以:

if(ev.hasOwnProperty('originalEvent')) {
    // Focus event was manually triggered.
}

To differentiate between keyboard and mouse based focus events, you could try binding a keydown handler to everything else to detect a Tab or Shift-Tab but that would be a gross hack and probably not reliable;为了区分基于键盘和鼠标的焦点事件,您可以尝试将keydown处理程序绑定到其他所有内容以检测TabShift-Tab但这将是一个严重的黑客攻击并且可能不可靠; for example, on an iPad, you don't hit Tab to move to the next field, you hit Next or Previous in the popup keyboard to move around and those may not register as key presses at all.例如,在 iPad 上,您没有按Tab键移动到下一个字段,而是在弹出键盘中按NextPrevious来移动,这些可能根本不会注册为按键。

There's a similar question about click events that might be of interest as well:还有一个类似的关于click事件的问题可能也很有趣:

In jQuery, how can I tell between a programmatic and user click? 在 jQuery 中,如何区分程序点击和用户点击?

As you note in the comments, you could trap click events to detect a mouse-based focus change and set a flag somewhere to remember it.正如您在评论中指出的那样,您可以捕获click事件以检测基于鼠标的焦点更改并在某处设置标志以记住它。 Then you'd have this:然后你会有这个:

  1. If there is no originalEvent in the jQuery event then the focus change was triggered manually (ie $x.focus() or similar).如果 jQuery 事件中没有originalEvent ,则手动触发焦点更改(即$x.focus()或类似的)。
  2. If the click handler flag is set then the focus change came from a mouse action.如果设置了单击处理程序标志,则焦点更改来自鼠标操作。
  3. Otherwise the focus change came from a keyboard event.否则焦点变化来自键盘事件。

You'd have to be careful that your click and focus events came in the right order and you'd need to make sure the flag was cleared when you're done with it.您必须注意单击和焦点事件的顺序正确,并且您需要确保在完成后清除标志。 This might not be bullet proof but maybe it doesn't need to be.这可能不是防弹的,但也许不需要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM