每次刷新頁面,倒數計時器都會重新加載。我發現我需要使用本地存儲(我猜),但我怎麼能夠在這個JavaScript倒計時代碼中實現呢? 這裏是我JS提琴 https://jsfiddle.net/BrsJsk/srv3ywnL/刷新倒計時
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t/1000) % 60);
var minutes = Math.floor((t/1000/60) % 60);
var hours = Math.floor((t/(1000 * 60 * 60)) % 24);
var days = Math.floor(t/(1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 59 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
<div id="clockdiv">
<p1 class="dayss"><span class="num days">34</span> days</p1>
<p1 class="hourss"><span class="num hours">16</span> hours</p1>
<p1 class="secondss"><span class="num seconds">1</span> secs</p1>
<p1 class="minutess"><span class="num minutes">19</span> mins</p1>
</div>
我猜你可以使用cookie ... – Sank6
@SankarshMakam本地存儲比Cookie更容易。在'window.unload'上,設置一個當前剩餘時間的本地存儲 - 'localStorage.setItem('clock',someVar)'然後在頁面加載,'if(localStorage.getItem('clock')){var deadline = localStorage.getItem( '時鐘'); }其他{var deadline = new Date(); }' –
你是說你希望倒計時暫停,然後在用戶回來時恢復?你需要像你說的那樣存儲。否則,如果你想讓它繼續倒計時,即使用戶離開了一段時間後又回來了,你需要及時開始倒計時到一個固定的位置。 –