我正在尝试向页面编写一些功能,但我无法将所有部分组合在一起:-(
我想要的只是简单的计数器,它计数到 0,然后显示消息(.confirmation)。如果您中断(移动鼠标或触摸键盘)计数器会暂停并显示不同的消息(警告),并在几秒钟后从头开始重复计数。噗……
我有用于监视用户操作和反对的元素,但我不知道如何将其添加在一起:
//monitors user action
$('.warning, .confirmation').hide();
$(document).bind('mousemove keydown', function() {
$('.warning').show().delay(2000).fadeOut(500);
});
//counts for example from 5 seconds (this value is in the <span></span> in html section)
var sec = $('#box span').text()
var timer = setInterval(function() {
$('#box span').text(--sec);
if (sec == 0) {
$('.confirmation').show(function() {
$(document).unbind();
});
clearInterval(timer);
}
}, 1000);
最佳答案
尝试类似的事情:
//countdown pause timer
var countDownPauseTimer = 0;
//monitors user action
$('.warning, .confirmation').hide();
$(document).bind('mousemove keydown', function() {
countDownPauseTimer = 10; // Countdown will pause for 10 seconds
$('.warning').show().delay(2000).fadeOut(500);
});
//counts for example from 5 seconds (this value is in the <span></span> in html section)
var sec = $('#box span').text()
var timer = setInterval(function() {
if (countDownPauseTimer > 0)
countDownPauseTimer--;
else
$('#box span').text(--sec);
if (sec == 0) {
$('.confirmation').show(function() {
$(document).unbind();
});
clearInterval(timer);
}
}, 1000);
我在这里所做的是引入另一个变量来指示我们正在暂停倒计时并保存暂停的剩余秒数。
在间隔刻度中,我检查是否有暂停并决定减少哪个值...
我没有测试它,但它应该可以工作。
更新
下面是更新后的代码,暂停结束后重新开始倒计时:
//countdown pause timer
var countDownPauseTimer = -1;
//monitors user action
$('.warning, .confirmation').hide();
$(document).bind('mousemove keydown', function() {
countDownPauseTimer = 10; // Countdown will pause for 10 seconds
$('.warning').show().delay(2000).fadeOut(500);
});
//counts for example from 5 seconds (this value is in the <span></span> in html section)
var sec = $('#box span').text();
var timer = setInterval(function() {
if (countDownPauseTimer > 0)
countDownPauseTimer--;
else if (countDownPauseTimer == 0) {
countDownPauseTimer--;
sec = $('#box span').text();
}
else
$('#box span').text(--sec);
if (sec == 0) {
$('.confirmation').show(function() {
$(document).unbind();
});
clearInterval(timer);
}
}, 1000);
关于jQuery 倒计时暂停和重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5633234/