Avoid element blur handler when window blur invoked (browser loses focus)

不问归期 提交于 2019-12-05 18:26:22

问题


To expound upon the question:

I've got an element which when clicked receives a sub-element. That sub-element is given a blur handler.

What I would like is for that handler not to be invoked when the browser loses focus (on window blur).

Towards that goal I've attempted several tacks, this being my current effort:

function clicked() {
    // generate a child element
    ...
    field = $(this).children(":first");
    $(window).blur(function () {
        field.unbind("blur");
    });
    $(window).focus(function () {
        field.focus();
        field.blur(function () {
            save(this);
        });
    });
    field.blur(function () {
        save(this);
    });
}

This doesn't work. What appears to be occurring is that when the browser loses focus, the field is losing focus first.


回答1:


Nice question!

This is possible, and fairly straightforward.

field.blur(function() {
    if(document.activeElement !== this) {
         // this is a blur that isn't a window blur
    }
});

JSFiddle

Or in vanilla JS:

field.addEventListener('blur', function() {
    if(document.activeElement !== this) {
         // this is a blur that isn't a window blur
    }
});

Edit: Though your answer deals with the browser losing focus, know that Firefox has unusal behavior (bug?) when returning to focus. If you have a input focused, and then unfocus the window, the element's blur is triggered (which is what the question was about). If you return to something other than the input, the blur event is fired a second time.




回答2:


A mildly dirty way to do this could be to use a setTimeout() prior to taking action.

var windowFocus;

$(window).focus(function() {
    windowFocus = true;
});

$(window).blur(function() {
    windowFocus = false;
});

function clicked() {
    // generate a child element
    ...

    field = $(this).children(":first");

    field.blur(function () {
        setTimeout(function() {
            if (windowFocus) {
                save(this);
            }
        }, 50);
    });
}


来源:https://stackoverflow.com/questions/19700476/avoid-element-blur-handler-when-window-blur-invoked-browser-loses-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!