我必须在我的在线测试网站上添加倒数计时器,但每次点击下一个或任何其他按钮时,计时器都会重置。我应该怎么做才能避免这种情况?这是我使用的代码
<span id="countdown-1">10 seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
alert('time finished');
return false;
document.getElementById(id).style.display = 'none';
}
}
答案 0 :(得分:0)
假设你知道你倒计时的日期。
<?php
$dueTime = mktime(0,0,0, 1, 1, 2015);
$secondsRemaining = $dueTIme - time();
?>
<span id="countdown-1"><?php echo $secondsRemaining; ?> seconds</span>
<script type="text/javascript">
// Initialize clock countdowns by using the total seconds in the elements tag
secs = parseInt(document.getElementById('countdown-1').innerHTML,10);
setTimeout("countdown('countdown-1',"+secs+")", 1000);
secs = parseInt(document.getElementById('countdown-2').innerHTML,10);
setTimeout("countdown('countdown-2',"+secs+")", 1000);
function countdown(id, timer){
timer--;
minRemain = Math.floor(timer / 60);
secsRemain = new String(timer - (minRemain * 60));
// Pad the string with leading 0 if less than 2 chars long
if (secsRemain.length < 2) {
secsRemain = '0' + secsRemain;
}
// String format the remaining time
clock = minRemain + ":" + secsRemain;
document.getElementById(id).innerHTML = clock;
if ( timer > 0 ) {
// Time still remains, call this function again in 1 sec
setTimeout("countdown('" + id + "'," + timer + ")", 1000);
} else {
// Time is out! Hide the countdown
alert('time finished');
return false;
document.getElementById(id).style.display = 'none';
}
}
答案 1 :(得分:0)
由于Javascript是客户端,因此每次刷新页面时都会刷新倒计时。
您必须对给定的timestamp
进行倒计时。
多亏了这一点,你将能够保持正确的计数。
这样的事情:(来自here的功能)
function getTimestamp(str) {
var d = str.match(/\d+/g); // extract date parts
return +new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]); // build Date object
}
var countdown = getTimestamp("2012-05-12 18:00:00") - (+new Date);
因为时间戳是未来的修复点!