2012-04-25 2 views
0

다음 코드가 있습니다. 카운트 다운은 작동하지만 창이 초점이 맞춰지지 않을 때 타이머가 멈추는 것은 작동하지 않습니다. 또한 창에 초점이 맞춰지면 카운트 다운을 다시 시작하고 싶습니다.jQuery에서 창에 포커스가 없을 때 카운터를 멈추게하려면 어떻게해야합니까?

아래 코드에서 $(document).blur() 이벤트는 작동하지 않지만 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); 

}); 
관련 문제