2012-04-25 8 views
0

私は次のコードを持っています。カウントダウンは機能しますが、ウィンドウがフォーカスされていないときのタイマーの停止は機能しません。また、ウィンドウがフォーカスしているときにカウントダウンを再開したいと思います。jQueryでは、ウィンドウにフォーカスがないときにカウンタを停止させるにはどうすればよいですか?

以下のコードでは、$(document).blur()イベントは機能しませんが、ぼかしをclick()に置き換えると動作します。 blur()とドキュメントに問題はありますか?

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

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

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

    }); 

答えて

3
var tm; 
$(document).ready(function(){  
    function countdown(){ 
     if (seconds > 0) { 
      seconds--; 
      $('#timer_div').text(seconds); 
      tm = setTimeout(countdown,1000); 
      } 
     if (seconds<=0){ 
      $('#timer').text('Go'); 
      } 
     } 

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

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

    }); 
+0

こんにちは、ありがとう。私はそれを試みたが、うまくいかなかった。ここに私のjsfiddleです。ありがとうございます。 – alexx0186

+0

'$(document).blur()'に問題があります。私がblurの代わりにclick()を使用すると、動作します.. blurイベントとドキュメントに問題はありますか? – alexx0186

+0

@ alexx0186は 'blur()の代わりに' $(document).mouseleave'を使います。 – mgraph

0

これを試してください:あなたの応答のための

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

function countdown(){ 

    if (seconds > 0) { 
     seconds--; 
     $('#timer_div').text(seconds); 
     counter=setTimeout(countdown,1000); 
     } 
    if (seconds<=0){ 
     $('#timer').text('Go'); 
     } 
    } 




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

}); 


$(document).blur(function(){ 
    clearTimeout(counter); 
    seconds++; 
    $('#timer').text(seconds); 

}); 
関連する問題