Determine what triggered focus event?

爷,独闯天下 提交于 2019-12-31 10:40:11

问题


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.


回答1:


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:

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

There's a similar question about click events that might be of interest as well:

In jQuery, how can I tell between a programmatic and user click?

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. Then you'd have this:

  1. If there is no originalEvent in the jQuery event then the focus change was triggered manually (i.e. $x.focus() or similar).
  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.



来源:https://stackoverflow.com/questions/6727005/determine-what-triggered-focus-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!