我正在尝试为预定的活动制作倒数计时器。一切都好,但无法获得完成时间通知。我的意思是当计时器完成时,它应该有一些自定义HTML而不是计时器,如'事件已启动'等。
你能帮助别人吗?提前致谢。
这是我正在尝试的代码和小提琴网址:
var target_date = new Date("Jan 30, 2014").getTime();
var days, hours, minutes;
var countdown = document.getElementById("countdown");
setInterval(function () {
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600 + 14);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
countdown.innerHTML = days + "<span> Day(s)</span>, " + hours + "<span> Hour(s)</span>, "
+ minutes + "<span> Min(s)</span>";
}, 1000);
答案 0 :(得分:0)
一种方法是检查剩下的时间。如果days
,hours
,minutes
和second
都是0
。
var countdownLoop = setInterval(function () {
// your calculation here
if (seconds < 0) {
clearInterval(countdownLoop);
countdown.innerHTML = "Event started!";
} else {
countdown.innerHTML = days + "<span> Day(s)</span>, " + hours + "<span> Hour(s)</span>, " + minutes + "<span> Min(s)</span>";
}
}, 1000);
clearInterval(countdownLoop);
因为不再需要而停止循环。
答案 1 :(得分:0)
您可以添加条件以清除间隔并显示其他文本:
if (seconds_left <= 0) { clearInterval(0); }
countdown.innerHTML =
seconds_left <= 0 ? "done!"
: days + "<span> Day(s)</span>, " + hours +
"<span> Hour(s)</span>, " +
+ minutes + "<span> Min(s)</span>"
但是你的代码并不是很好。 1 随意使用和摆弄this jsFiddle 2
1 尝试使用
运行它var target_date = new Date;
target_date.setSeconds(target_date.getSeconds()+5);
它显示剩余时间0 Day(s), 14 Hour(s), 0 Second(s)
2 要使用您的日期值运行,请更改代码行
timeouttime = new Date('2014/01/30').getTime(),
// and after initialize
d.querySelector('#timeout').value =
Math.floor( ( timeouttime - new Date().getTime() ) / 1000 );
doSet();
btn.click();
这是初始jsFiddle的fork
答案 2 :(得分:0)
var target_date = new Date(“2014年1月28日”)。getTime(); var days,hours,minutes; var countdown = document.getElementById(“countdown”);
var interv = setInterval(function () {
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600 + 14);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
countdown.innerHTML = days + "<span> Day(s)</span>, " + hours + "<span> Hour(s)</span>, " + minutes + "<span> Min(s)</span>";
if ((seconds + minutes + hours + days) <= 0) {
clearInterval(interv);
myFunc();
}
}, 1000);
function myFunc() {
//code
}
谢谢,