基本上你需要保存倒計時,並在每次加載頁面時都返回。
下面的代碼段應該能夠做到。調用get12HourPeriod將從當前日期開始添加12小時並保存到cookie中。只要你不通過true
它,每一頁重新加載將從cookie獲得值,你的倒計時應該繼續正常。如果您通過了true
參數,那麼它將刪除該Cookie,然後運行(或重新連接點擊)將保存新的12小時時間段。
<script type="text/javascript">
function get12HourPeriod(reset) {
if (reset) { // remove date from cookie
document.cookie = 'countdownTo=;expires=Thu, 01 Jan 1970 00:00:01 GMT;'; // remove cookie date
return;
}
if (document.cookie.indexOf('countdownTo=') == -1) { // create cookie if not exists
var today = new Date(); // get current date
today.setHours(today.getHours() + 12); // add 12 hours to it
document.cookie = 'countdownTo=' + today.getTime() + ';expires=' + today.toGMTString(); // create cookie in milliseconds
}
var cookies = document.cookie; // get all cookies
cookies = cookies.substr(cookies.indexOf('countdownTo='), cookies.length); // get only the cookie we need it
if (cookies.indexOf(';') != -1) { // make sure only our cookie is returned
cookies = cookies.substr(0, cookies.indexOf(';'));
}
cookies = cookies.split('=')[1]; // get cookie value
return new Date(parseInt(cookies, 10)); // parse the milliseconds saved and return the countdown as date
}
$(function() {
$('#defaultCountdown').countdown({ until: get12HourPeriod() });
$('#removeCountdown').toggle(function() {
$(this).text('Re-attach');
$('#defaultCountdown').countdown('destroy');
get12HourPeriod(true); // passing true here will reset the countdownTo
},
function() {
$(this).text('Remove');
$('#defaultCountdown').countdown({ until: get12HourPeriod() });
});
});
</script>
需要定期記錄時間,當頁面加載 – renakre
服務器,Cookie或localStorage的 – mplungjan
所以基本上這個倒計時是行不通的,因爲它應該be.are有其他人做到這一點從那裏看了嗎? –