如何判断焦点去哪里了?
此处已提出此问题< /a> 之前,但是是几年前的事了,当时还没有跨平台的解决方案(除了 setTimeout
解决方案,这确实不是很方便)。
我想做 onblur="foo(parm);"
并让 foo
能够确定哪个元素现在具有焦点。
我正在使用常规的 javascript;请不要使用 jQuery。
如今这可能吗?
This has been asked here before, but several years ago, and there was no cross-platform solution at the time (other than the setTimeout
solution, which is really not very handy).
I'd like to do onblur="foo(parm);"
and have foo
be able to determine which element now has focus.
I'm using regular javascript; no jQuery for this one, please.
Is that possible these days?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以尝试这样的事情:
编辑:
You can try something like this:
EDIT:
在 jQuery 中,应 OP 的要求:
In jQuery, at the OP's request:
有趣的问题。问题的核心是 - “焦点”事件何时触发,在模糊事件之前还是之后?如果它在模糊事件之前触发,问题很容易,因为您只需将当前焦点存储在模糊事件可以访问的变量中。
然而,至少在 Chrome 13 中,模糊事件似乎发生在焦点事件之前。一种可能的解决方案。
给定以下 HTML:
然后您可以:
基本上,我只是不执行模糊回调,因此在我们知道哪个元素获得焦点后调用焦点事件会很方便。
这是 JSFiddle 上的工作示例。
编辑:此解决方案存在这样的问题:如果您通过单击其他表单元素之外的其他内容来模糊表单,则模糊事件永远不会触发(因为我们等待焦点事件)。我能想到的唯一解决方法是使用计时器来检查是否定义了pendingBlur,如果是,则调用它。此时您实际上不再需要焦点事件来调用模糊回调......
Interesting question. The heart of the matter is - when does the 'focus' event fire, before or after the blur event? If it fires before the blur event, the problem is easy, because you can just store the current focus in a variable that your blur event can access.
However, at least in Chrome 13, it appears the blur event happens before the focus event. One possible solution.
Given the following HTML:
You can then:
Basically, I just not the blur callback so it is handy for the focus event to call after we know about which element was focused.
Here is a working example on JSFiddle.
EDIT: This solution suffers from the problem that if you blur on the form by clicking on something other than another form element, the blur event never fires (since we wait for the focus event). The only way around that, that I can conceive, is using a timer to check if pendingBlur is defined, and if so, call it. At which point you don't really need the focus event to call the blur callback anymore...
2020 年:所有主要浏览器(桌面版和移动版)均支持 FocusEvent。相关目标。
Year 2020: All major browsers (desktop and mobile) support FocusEvent.relatedTarget.
event.latedTarget
找不到新聚焦的元素(在我的例子中是div
类型),但只返回null
。在元素上附加属性
tabindex="0"
后,现在它可以工作了。tabindex
是一个使元素可以使用键盘上的 Tab 键获得焦点的属性。我想这主要是为了网络可访问性。我猜你不需要设置
tabindex
属性,只要焦点元素已经可以通过 Tab 键访问(例如a
、select< /代码>..等等)
event.relatedTarget
couldn't find the newly-focused element(wasdiv
type in my case), but onlynull
gets returned.After attaching the attribute
tabindex="0"
on the element, now it works.tabindex
is an attribute that make elements focusable using tab key on keyboard. I guess it is mainly for web accessibility.And I guess you won't need to set
tabindex
attribute as long as to-be focused elements are already accessible by tab key (such asa
,select
.. and so on)