更改浏览器选项卡会引发焦点事件,特别是在Google Chrome中 [英] Changing browser tabs undesirably fires the focus event, especially in Google Chrome

查看:213
本文介绍了更改浏览器选项卡会引发焦点事件,特别是在Google Chrome中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到焦点事件有一个小问题。显然,当切换到另一个浏览器选项卡然后再返回时,焦点会激发。我宁愿没有那样的事情发生;有可能吗?

I've got a little issue with the focus event that I just became aware of. Apparently, focus fires when switching to another browser tab and then back again. I'd rather not have that happen; is it possible?

直到今天,我从未意识到这一点。这里有一个小小的演示: http://jsfiddle.net/MJ6qb/1/

I was never aware of this until today. Here's a little demo: http://jsfiddle.net/MJ6qb/1/

var times = 0;
$('input').on('focus', function() {
    times ++;
    $(this).after('<br>Focused '+times+' times');   
});

重现:专注于输入,然后切换浏览器选项卡,然后切换回来。所有浏览器似乎在切换回选项卡时触发焦点事件,并且 Google Chrome 19正在两次触发它

To reproduce: Focus on the input, then switch browser tabs, then switch back. All browsers seem to fire the focus event when you switch back to the tab, and Google Chrome 19 is firing it twice!

理想情况下,函数不应该在切换浏览器选项卡时运行,但只能在用户单击或 Tab 上运行,但现在我知道Chrome问题了,我更关心一点,因为它会导致额外的我的真实应用程序中的不需要的背靠背AJAX请求(它用于获取需要更新的自动完成的结果,但不是我想要使用的关键事件)。

Ideally, the function should not run when switching browser tabs at all but only on user click or Tab, but now that I'm aware of the Chrome issue I'm a bit more concerned about that because it's resulting in extra unwanted back-to-back AJAX requests in my real app (it's for fetching results for an autocomplete that needs to be up to date, but not so much that I want to use the keyup event).

它似乎没有jQuery相关(我曾用香草javascript进行过测试),但是我可以使用jQuery来获得解决方案。我能做些什么吗?我知道我可以使用jQuery的 one(),但我确实希望该函数运行多次。

It doesn't seem jQuery related (I did test with vanilla javascript) but I can using jQuery for a solution. Is there anything I can do about this? I know I can use jQuery's one() but I do want the function to run more than once.

推荐答案

试试这个

var times = 0;
var prevActiveElement;

    $( window ).on( "blur", function(e){
            prevActiveElement = document.activeElement;
    });

    $('input').on('focus', function() {
        if (document.activeElement === prevActiveElement) {
            return;
        }
        prevActiveElement = document.activeElement;
        times++;
        $(this).after('<br>Focused ' + times + ' times');
    }).on( "blur", function(){
        prevActiveElement = null;  
    });​

这篇关于更改浏览器选项卡会引发焦点事件,特别是在Google Chrome中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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