簡體   English   中英

調用窗口模糊時避免使用元素模糊處理程序(瀏覽器失去焦點)

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

解釋這個問題:

我有一個元素,當點擊時會收到一個子元素。 該子元素被賦予模糊處理程序。

我想要的是,當瀏覽器失去焦點時(窗口模糊),不要調用該處理程序。

為了達到這個目標,我嘗試了幾個方法,這是我目前的努力:

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);
    });
}

這不起作用。 似乎正在發生的事情是,當瀏覽器失去焦點時,該領域首先失去焦點。

好問題!

這是可能的,而且相當簡單。

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

的jsfiddle

或者在香草JS中:

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

編輯:雖然你的答案處理瀏覽器失去焦點,但知道Firefox在返回焦點時有不尋常的行為(錯誤?)。 如果您有一個聚焦的輸入,然后取消聚焦窗口,則會觸發元素的模糊(這就是問題所在)。 如果返回到輸入以外的其他內容,則會再次觸發blur事件。

一種稍微骯臟的方法可能是在采取行動之前使用setTimeout()

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);
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM