【发布时间】:2015-05-11 00:34:11
【问题描述】:
目前我有一个脚本,它有一个特定日期的倒计时,但我希望倒计时在计时器上是特定的,所以假设我启动计时器并且我已将计时器设置为运行 30 天,然后它将运行 30 天,然后再次重置为 30 天并开始运行。是否可以更改它来这样做?
我的代码:
<body>
<span id="countdown"></span>
<script LANGUAGE="Javascript">
// set the date we're counting down to
var target_date = new Date("Apr 9, 2015").getTime();
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countdown = document.getElementById("countdown");
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
countdown.innerHTML = days + "d, " + hours + "h, "
+ minutes + "m, " + seconds + "s";
}, 1000);
</script>
</body>
编辑:
我现在已将代码更改为如下所示,但是现在当我在浏览器中打开网站时,它是空白的。
新代码:
<span id="countdown"></span>
<script LANGUAGE="Javascript">
// set the date we're counting down to
var target_date = new Date("Apr 9, 2015").getTime();
// variables for time units
var days, hours, minutes, seconds;
// get tag element
var countdown = document.getElementById("countdown");
if (seconds_left <= 0){
target_date = target_date + 30 days;
}
// update the tag with id "countdown" every 1 second
setInterval(function () {
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
countdown.innerHTML = days + "d, " + hours + "h, "
+ minutes + "m, " + seconds + "s";
}, 1000);
【问题讨论】:
-
当
seconds_left <= 0重新计算target_datetarget_date+ 30 天。 -
您真的想在浏览器中安装这么大的计时器吗?无论如何,您始终可以在到达时间时使用
clearInterval()清除间隔并重新开始。 -
我现在已经添加了这一行
if (seconds_left <= 0){ target_date = target_date + 30 days; }但是现在我的页面上什么都不会显示,它只是空白,在它显示倒计时之前在哪里?
标签: javascript html timer reset countdown