javascript 为什么 $(document).blur() 和 $(document).focus() 不适用于 Safari 或 Chrome?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10325132/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:28:43  来源:igfitidea点击:

Why is $(document).blur() and $(document).focus() not working with Safari or Chrome?

javascriptjqueryhtml

提问by alexx0186

I am making a counter which counts down when document is on focus. It stops counting down when it's on blur.

我正在制作一个计数器,当文档处于焦点时它会倒计时。当它处于模糊状态时,它会停止倒计时。

It is working in FF, but with Safari and Chrome, the counter doesn't work at all.

它在 FF 中工作,但在 Safari 和 Chrome 中,计数器根本不起作用。

Is there a compatibility problem with Safari/Chrome?

Safari/Chrome 是否存在兼容性问题?

All I'm using is $(document).blur()and $(document).focus(), and there are both within a $(document).ready()block.

我使用的只是$(document).blur()and $(document).focus(),并且两者都在一个$(document).ready()块中。

var tm;
$(document).ready(function(){   

        var seconds = 50;
        $('#timer').html(seconds);
        countdown();

    $(window).focus(function(){
         function countdown(){ 
         if (seconds > 0) {
            seconds--; 
            $('#timer').text(seconds);
            tm = setTimeout(countdown,1000);
            }
        if (seconds<=0){ 
            $('#timer').text('Go');
            }   
        }); 



    $(window).blur(function(){
        clearTimeout(tm);
        seconds++;
        $('#timer').text(seconds);

    });
});

回答by Dmytro Shevchenko

I've always used $(window).focus()and $(window).blur(). Try these instead.

我一直使用$(window).focus()$(window).blur()。试试这些吧。

Also, note that in FF and IE the "focus" event fires on ~document load, while in Chrome and Safari it only fires if the window had lost focus before and now it has regained it.

另外,请注意,在 FF 和 IE 中,“focus”事件在 ~document load 时触发,而在 Chrome 和 Safari 中,它仅在窗口之前失去焦点而现在重新获得焦点时触发。

UPD:Now as you pasted your code, I reworked it to (hopefully) fit your purpose:

UPD:现在,当您粘贴代码时,我对其进行了修改以(希望)符合您的目的:

var tm;
var seconds = 50;
var inFocus = true;

function countdown() {
    if (seconds > 0) {
        seconds--;
    }

    if (seconds <= 0) {
        $('#timer').text('Go');
    }
    else {
        $('#timer').text(seconds);
        tm = setTimeout(countdown, 1000);
    }
}

$(function() {
    $('#timer').html(seconds);
    countdown();

    $(window).focus(function() {
         if(!inFocus) {
             countdown();
         }
    });

    $(window).blur(function() {
        inFocus = false;
        clearTimeout(tm);
        seconds++;
        $('#timer').text(seconds);
    });
});