每当我刷新页面时,计时器都会重置。它从头开始。我使用了名为 countdown.js 的插件
这是代码:
<script type="text/javascript">
var now = new Date();
var countTo = 30 * 24 * 60 * 60 * 1000 + now.valueOf();
$('.timer').countdown(countTo, function(event) {
var $this = $(this);
switch(event.type) {
case "seconds":
case "minutes":
case "hours":
case "days":
case "weeks":
case "daysLeft":
$this.find('span.'+event.type).html(event.value);
break;
case "finished":
$this.hide();
break;
}
});
</script>
<div class="col-md-8 col-md-offset-3 timer">
<div class="days-wrapper" style="text-align:center;">
<span class="days"></span>
<p style="margin-left:-80px;"><br><br>DAYS</p>
</div>
<div class="hours-wrapper" style="text-align:center;">
<span class="hours"></span>
<p style="margin-left:-80px;"><br><br>HOURS</p>
</div>
<div class="minutes-wrapper" style="text-align:center;">
<span class="minutes"></span>
<p style="margin-left:-80px;"><br><br>MIN</p>
</div>
</div>
最佳答案
每次您重新加载页面时,javascript 都会“忘记”您之前所做的一切,并且您的代码会完全从头开始执行。
一个可能的解决方案是使用一些持久存储方法,例如 localStorage
在您的示例中,您可以执行以下操作:
var previousCountTo = localStorage.getItem('time');
var now = new Date();
var countTo = previousCountTo?parseInt(previousCountTo, 10):(30 * 24 * 60 * 60 * 1000 + now.valueOf());
localStorage.setItem('time', countTo); // Save the current time.
$('.timer').countdown(countTo, function(event) {
var $this = $(this);
console.log(event);
switch(event.type) {
case "seconds":
case "minutes":
case "hours":
case "days":
case "weeks":
case "daysLeft":
$this.find('span.'+event.type).html(event.value);
break;
case "finished":
$this.hide();
localStorage.removeItem('time'); // once finished, remove the timer.
break;
}
});
关于javascript - 我使用了倒数计时器,但它会自行重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909614/