【问题标题】:Why is $(document).blur() and $(document).focus() not working with Safari or Chrome?为什么 $(document).blur() 和 $(document).focus() 不适用于 Safari 或 Chrome?
【发布时间】:2012-04-25 23:17:12
【问题描述】:

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

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

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

我使用的是$(document).blur()$(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);

    });
});

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

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

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

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

    【讨论】:

    • 您好,感谢您的回复。我试过你的方法。它仅适用于第二个焦点。但是计数器不是从 (window).focus() 开始的。有没有办法解决这个问题,即使它需要更多的代码?非常感谢
    • 我已经解释了不计算Chrome中第一个焦点的原因。我用跨浏览器解决方案更新了我的答案(或者我认为)。
    • 您好,感谢您的解决方案。我只是不明白我应该在 if 语句中添加什么。 // count = 1;// count++; 有什么区别?非常感谢你的帮助。问候
    • @alexx0186 if 状态仅在文档加载时执行一次。如果浏览器是 Chrome 或 Safari,它定义计数器的初始值。并且count++ 在每次窗口获得焦点时执行,计数器递增。我不确定 = 1 和 ++ 是否是您所需要的,因为您没有详细描述您希望计数器如何工作。
    • @alexx0186 现在我了解您想要实现的目标。看看我更新的答案中的代码。
    猜你喜欢
    • 1970-01-01
    • 2014-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多