簡體   English   中英

為什么$(document).blur()和$(document).focus()不能與Safari或Chrome一起使用?

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

我正在制作一個計數器,當文檔處於焦點時會倒計時。 它在模糊時停止倒計時。

它在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);

    });
});

我總是使用$(window).focus()$(window).blur() 試試這些。

此外,請注意,在FF和IE中,“焦點”事件會觸發〜文檔加載,而在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);
    });
});

暫無
暫無

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

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