JavaScript FocusOut - 获取获得焦点的元素 [英] JavaScript FocusOut - get the element that receives focus

查看:122
本文介绍了JavaScript FocusOut - 获取获得焦点的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当引发 FocusOut 事件时,您如何知道哪个元素获得焦点

When the FocusOut event is raised, how do you know which element receives the focus?

正确的方法似乎是使用事件的 relatedTarget 属性。但是,这似乎并不适用于所有浏览器:

The correct way seems to be to use the event's relatedTarget property. However, this seems not to work in all browsers:


  • 在谷歌浏览器中,它可以正常工作

  • 在Firefox和Internet Explorer中,relatedTarget为null

  • 在Safari中,relatedTarget属性甚至不存在

我找到了一个只在IE中工作的解决方法(使用document.activeElement),但我想知道是否有一个通用解决方案已经证明可以在所有主流浏览器中使用

I have found a workaround which works only in IE (using document.activeElement), but I'm wondering if there isn't a general solution that has proven to work in all major browsers.

虽然我可以找到类似的问题和答案,但我找不到任何适用于所有浏览器的解决方案。

Although I can find similar questions and answers, I haven't found any solution which really works in all browsers.

编辑:下面的例子显示了我的意思。

the example below shows what I mean.

HTML:

<input id="text1" type="text" value="first" />
<input id="text2" type="text" value="second" />

Javascript / JQuery:

Javascript/JQuery:

$('#text1').focusout(function(e) {
    // At this point, I want to know which element is receiving the focus (i.e. text2)
    alert(e.relatedTarget); // works in Chrome
    alert(document.activeElement); // works in IE
    // both do not work in Firefox or Safari
});


推荐答案

我有一个firefox的假设和解决方法。 document.activeElement似乎有效。然后聚焦命中,所以它被删除。当焦点击中(或者可能紧接着)时,将再次出现焦点元素。但是在out和in之间没有任何重点,所以没有任何元素被报告为活动。

I have a hypothesis and workaround for firefox. document.activeElement seems to work. Then focusout hits, so it gets removed. By the time focusin hits (or maybe immediately after) there will be a focused element again. But between out and in there is nothing focused, so no element is being reported as active.

我的解决方法是一个愚蠢的setTimeout hack。 setTimeout(function(){console.log(document.activeElement)},1); 可靠地为我提供了一个活动元素。当然,我只在一台机器上进行了测试,花了90秒才完成,但这是迄今为止我发现的最好的。

My workaround is a stupid setTimeout hack. setTimeout( function() {console.log(document.activeElement)}, 1); reliably gets me an active element. Granted I've only tested in one machine and spent all of 90 seconds doing so, but it's the best I've found so far.

这篇关于JavaScript FocusOut - 获取获得焦点的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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