我有一个简单的要求。
上面的代码允许我显示倒计时。有什么办法在倒计时进行时进行回调吗?第一个在15秒之后,这样我就可以隐藏显示倒计时的div,在过期前1分钟,再次显示它,并在结束时显示JavaScript弹出?
坦斯克帮了我
发布于 2016-12-15 16:46:25
我假设您已经知道如何隐藏、显示或更改HTML标记的内部文本,并且它已经位于HTML的正确位置。让我们集中讨论倒计时应如何运作:
$(function() {
//Initialization
var minutes = 30;
var seconds = 0;
//Make sure your div exists
var countDownContext = $("#divCountdown");
//Showing things initially
countDownContext.text(minutes + ":" + seconds);
//15 seconds
var initialTime = 15;
//We store the interval to be able to stop the repetition later
var myInterval = setInterval(function() {
//Are we still inside those 15 seconds at the start?
if (initialTime > 0) {
//Was this the last second?
if (--initialTime === 0) {
//Then hide
countDownContext.hide();
}
}
//We decrease seconds and check whether it, before decreasing was 0
if (seconds-- === 0) {
//If it was, then we decrease a minute and set seconds to 59
minutes--;
seconds = 59;
}
//Refresh inner text
countDownContext.text(minutes + ":" + seconds);
//Is the last minute reached?
if ((minutes === 1) && (seconds === 0)) {
//Then show
countDownContext.show();
}
//Is the time expired?
if ((minutes <= 0) && (seconds <= 0)) {
//Then alert about it
alert("Your time is up");
//And clear the interval
clearInterval(myInterval);
}
}, 1000);
});编辑:
这里描述的逻辑可以与您打算使用的插件一起使用,请看一下这示例。
发布于 2016-12-15 16:44:52
查看文档http://hilios.github.io/jQuery.countdown/documentation.html#event-object,事件对象提供对倒计时中剩余的总分钟/总秒的访问,您可以将其与update.countdown和finish.countdown事件组合起来,如下所示
$("#divCountdown")
.countdown(timeToExpire, function (event) {
$(this).text(
event.strftime('%M:%S')
);
}).on('update.countdown',function(event) {
//check event.offset.totalMinutes value to show/hide object
}).on('finish.countdown',function(event){
//display alert
});发布于 2016-12-15 16:52:55
您已经每秒钟调用一个处理程序,所以只需做一些计算就可以确定经过的/剩余的时间:
var $countdown = $("#divCountdown"),
countdownMinutes = 30,
timeStart = new Date().getTime(),
timeEnd = timeStart + countdownMinutes * 60 * 1000;
$countdown
.countdown(timeEnd, function (e) {
var now = e.timeStamp,
secondsElapsed = Math.floor((now - timeStart) / 1000),
secondsRemaining = Math.ceil((timeEnd - now) / 1000);
$countdown.text(e.strftime('%M:%S'));
switch (secondsElapsed) {
case 15:
$countdown.hide();
break;
}
switch (secondsRemaining) {
case 60:
$countdown.show();
break;
}
})
.on('finish.countdown', function (e) {
setTimeout(function () {
alert('boom');
});
});https://stackoverflow.com/questions/41168907
复制相似问题