调用窗口模糊时避免使用元素模糊处理程序(浏览器失去焦点) [英] Avoid element blur handler when window blur invoked (browser loses focus)

查看:163
本文介绍了调用窗口模糊时避免使用元素模糊处理程序(浏览器失去焦点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要解释这个问题:

我有一个元素,当点击时会收到一个子元素。该子元素被赋予一个模糊处理程序。

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.

推荐答案

好问题!

这是可能的,而且相当简单。

This is possible, and fairly straightforward.

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有不寻常的行为(错误?)。如果您有一个聚焦的输入,然后取消聚焦窗口,则会触发元素的模糊(这就是问题所在)。如果您返回到输入以外的其他内容,则会在时间内触发模糊事件。

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.

这篇关于调用窗口模糊时避免使用元素模糊处理程序(浏览器失去焦点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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