我正在制作一个计数器,当文档处于焦点时会倒计时。它会在模糊时停止倒计时。
它在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);
});
});
答案 0 :(得分:12)
我一直使用$(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);
});
});