从onBlur事件中获取新聚焦的元素(如果有)。 [英] Get the newly focussed element (if any) from the onBlur event.

查看:617
本文介绍了从onBlur事件中获取新聚焦的元素(如果有)。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在执行onBlur处理程序时获取新聚焦的元素(如果有的话)。

I need to get the newly focussed element (if any) while executing an onBlur handler.

我该怎么做?

我可以想到一些可怕的解决方案,但没有任何不涉及setTimeout。

I can think of some awful solutions, but nothing which doesn't involve setTimeout.

推荐答案

引用它:

document.activeElement

不幸的是,当模糊事件发生时,新元素没有被聚焦,因此这将报告正文。所以你必须用标志和焦点事件来破解它,或者使用setTimeout。

Unfortunately the new element isn't focused as the blur event happens, so this will report body. So you are gonna have to hack it with flags and focus event, or use setTimeout.

$("input").blur(function() {
    setTimeout(function() {
        console.log(document.activeElement);
    }, 1);
});​

工作正常。

如果没有setTimeout,您可以使用:

Without setTimeout, you can use this:

http: //jsfiddle.net/RKtdm/

(function() {
    var blurred = false,
        testIs = $([document.body, document, document.documentElement]);
    //Don't customize this, especially "focusIN" should NOT be changed to "focus"
    $(document).on("focusin", function() {

        if (blurred) {
            var elem = document.activeElement;

            blurred = false;

            if (!$(elem).is(testIs)) {
                doSomethingWith(elem); //If we reached here, then we have what you need.
            }

        }

    });
    //This is customizable to an extent, set your selectors up here and set blurred = true in the function
    $("input").blur(function() {
        blurred = true;
    });

})();​

//Your custom handler
function doSomethingWith(elem) {
     console.log(elem);
}

这篇关于从onBlur事件中获取新聚焦的元素(如果有)。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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