Pet*_* M. 10 javascript focusout
当事件的内容时引发的事件,你怎么知道哪些元素获得焦点?
正确的方法似乎是使用事件的relatedTarget属性.但是,这似乎不适用于所有浏览器:
我找到了一个只在IE中工作的解决方法(使用document.activeElement),但我想知道是否有一个通用的解决方案已被证明可以在所有主流浏览器中使用.
虽然我可以找到类似的问题和答案,但我找不到任何真正适用于所有浏览器的解决方案.
编辑:下面的例子显示了我的意思.
HTML:
document.getElementById('text1').addEventListener('focusout', function(e) {
// At this point, I want to know which element is receiving the focus (i.e. text2)
console.log(e.relatedTarget); // works in Chrome
console.log(document.activeElement); // works in IE
// both do not work in Firefox or Safari
});Run Code Online (Sandbox Code Playgroud)
使用Javascript/JQuery的:
<input id="text1" type="text" value="first" />
<input id="text2" type="text" value="second" />Run Code Online (Sandbox Code Playgroud)
我有一个关于Firefox的假设和解决方法。document.activeElement似乎有效。然后聚焦击中,因此将其删除。当focusin命中时(或之后不久),将再次有一个聚焦的元素。但是,从内到外之间没有任何重点,因此没有元素被报告为活动的。
我的解决方法是一个愚蠢的setTimeout hack。 setTimeout( function() {console.log(document.activeElement)}, 1);确实使我成为活跃分子。当然,我只在一台机器上进行过测试,并花了90秒钟来完成所有测试,但这是迄今为止我发现的最好的结果。