我有一个简单的要求。
到期时,会显示一条javascript警告,告诉用户时间到了。
$("#divCountdown")
.countdown(timeToExpire, function (event) {
$(this).text(
event.strftime('%M:%S')
);
//15 seconds later do something
//1740 seconds later, i.e. 29 minutes, do something
//1800 seconds later, i.e. 30 minutes, do something
})
以上代码允许我显示倒计时。在倒计时进行过程中有没有办法进行回调? 15秒后的第一个,以便我可以隐藏显示倒计时的div,到期前1分钟,再次显示,最后显示JavaScript弹出窗口?
Thansk帮忙
答案 0 :(得分:2)
查看文档http://hilios.github.io/jQuery.countdown/documentation.html#event-object,事件对象提供对倒计时剩余的totalMinutes / totalSeconds的访问权限,您可以将其与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
});
答案 1 :(得分:2)
你已经每秒都有一个处理程序被调用,所以只需要做一些数学运算来确定已用时间/剩余时间:
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');
});
});
答案 2 :(得分:0)
我将假设您已经知道如何隐藏,显示或更改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 = setTimeout(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);
});
编辑:
此处描述的逻辑可以与您打算使用的插件一起使用,请查看this示例。