我如何将当前计时器的时间传递到下一页?
计时器代码
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds()/10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds: seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds: milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
我正在使用
<h3 style="color: #ff0000; margin: 0; padding: 0; font-size: 100%;font-weight:normal; font-family: robotolight;"> You have <div id="timer"></div> to complete the game!
在我的HTML中。
有没有办法传递div id ='timer'&gt;进入下一页?
感谢。
答案 0 :(得分:1)
重新加载页面或加载新页面意味着重新加载javascript,因为它在当前页面的上下文中运行。有一种很好的方法可以将javascript变量传递给新页面;它需要某种形式的数据持久性。 Cookies和localStorage是持久化数据客户端的两种最常用的方法。
客户端cookie被写入浏览器缓存,并且在HTTP标头中是透明的。 LocalStorage是一种较新的机制,但得到了很好的支持,允许最多5MB的浏览器存储空间而无需传入标题。
在您的用例中,不是存储计时器,而是在计时器启动时存储时间戳可能是有意义的。这样,它可以在下一页中从这一个静态起始值重新计算。
var timerStart;
var expireDate = new Date();
function displayTimer(){
var now = new Date().getTime();
var timerStart = timerStart || cookieTimer();
val timeDiff = now - timerStart;
document.getElementById("timer").innerHTML = timeDiff.toString();
if(timeDiff > expireDate.getTime()) clearInterval(timerInterval);
}
val timerInterval = setInterval(displayTimer, 1);
// Using cookies
function cookieTimer(){
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
function setCookie(cname, cvalue, expireDate) {
var d = new Date();
d.setTime(d.getTime() + expireDate.getTime());
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
var timerCookie = getCookie("timer");
if(timerCookie !== "") return new Date(timerCookie).getTime());
else {
setCookie("timer", timerStart, expireDate);
return new Date().getTime();
}
}
// Using localStorage
function localStorageTimer(){
function setLocalStorageObject(key, obj, expireDate){
obj.expires = expireDate.getTime();
localStorage.setItem(key, JSON.stringify(obj));
}
function getLocalStorageObject(key){
val item = localStorage.getItem(key);
if(item) return JSON.parse(item);
else return {};
}
var timerLocal = getLocalStorageObject("timer");
var now = new Date().getTime();
if(timerLocal && timerLocal.startTime && timerLocal.expires > now) return timerLocal.startTime;
else {
setLocalStorageObject("timer", { startTime: now });
return now;
}
}