确定什么触发焦点事件? [英] Determine what triggered focus event?

查看:137
本文介绍了确定什么触发焦点事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要确定引起焦点事件的原因。

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.

我该怎么做?

我正在看事件对象,但我'没有看到任何东西太有用了。

I'm looking at the event object, but I'm not seeing anything too useful.

推荐答案

如果焦点来自 $ x.focus )呼叫,则事件将不会有一个 originalEvent 属性,因为浏览器没有事件:

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

为了区分基于键盘和鼠标的焦点事件,您可以尝试绑定 keydown 处理程序到所有其他检测标签 Shift-Tab ,但这将是一个严重的黑客,可能不可靠;例如,在iPad上,您不要点击 Tab 移动到下一个字段,您在弹出式键盘中点击下一步上一页要移动,那些可能不会注册为按键。

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:


正如您在注释中注释的那样,您可以捕获单击事件以检测基于鼠标的焦点更改并设置标志在某处记住它。那么你会有这样的:

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. 如果在jQuery中没有 originalEvent 事件然后焦点更改被手动触发(即 $ x.focus()或类似)。

  2. 如果点击处理程序标志是

  3. 否则焦点更改来自键盘事件。

  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.

这篇关于确定什么触发焦点事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆