js cookie 頁面倒計時
阿新 • • 發佈:2019-10-07
if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length;; return unescape(document.cookie.substring(c_start,c_end)) } } return ""
}
function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
實現步驟
點選加購 -> 記錄點選當前時間 ->設定個cookie
在點選頁面:
function payment() {
var n = getCookie('now_time'); if(!n){ var nowtime = new Date(); nowtime= nowtime.getTime(); setCookie('now_time',nowtime,5); } }
在支付頁面呼叫方法:
now:當前的時間戳
function PaymentCountdown(now){
var now = now; var w = getCookie('now_time'); if(w){ var timeout =setInterval(function(){ var dateTime = new Date(); dateTime = dateTime.getTime(); var diff = dateTime - now; var alltime = 5*60*1000; var c = alltime-diff; if(c>=0){ var m = Math.floor(c/1000/60%60); var s = Math.floor(c/1000%60); var str = "<span>"+m+"</span>:<span>"+s+"</span>"; jQuery("#payment_time").html(str); }else if(c<0){ clearInterval(timeout); jQuery("#payment_words").hide(); jQuery("#payment_end").show(); } }, 1000); }
};
原文地址:https://segmentfault.com/a/1190000016864154
更多專業前端知識,請上 【猿204