在原贴的基础上改进了一下。基于jquery+cookie实现在线考试倒计时,关闭浏览器后重新打开后依然可以计时。一下代码在本地测试,由于chrome浏览器只支持web的cookie。在实际中倒计时的总时长应从后台获取。
<body>
<script type="text/javascript">
$(function() {
var _minute = parseInt("1");//"1" 倒计时 多长时间,分钟为单位
var _expiresHours = _minute * 60 * 1000;
if(!hasSetCookie()){
//xxxx是cookie的标示,以下均是
addCookie("xxxx", _expiresHours, _expiresHours);
}
settime($("#remainTime"));
});
function hasSetCookie(){
var strCookie = document.cookie;
var arrCookie = strCookie.split("; ");
for (var i = 0; i < arrCookie.length; i++) {
var arr = arrCookie[i].split("=");
if (arr[0] == "xxxx") {
return true;
}
}
return false;
}
//开始倒计时
function settime(remainTime) {
var _time = getCookieValue("871d31bacfd4451484c5f70f8860c2a9");
var _countdown = parseInt(getCookieValue("xxxx")) / 1000;
if (_countdown == -1) {
alert("考试时间到!");
endExam();
} else {
var _second = _countdown % 60;
var _minute = parseInt(_countdown / 60) % 60;
var _hour = parseInt(parseInt(_countdown / 60) / 60);
if (_hour < 10)
_hour = "0" + _hour.toString();
if (_second < 10)
_second = "0" + _second.toString();
if (_minute < 10)
_minute = "0" + _minute.toString();
remainTime.html(_hour + ":" + _minute + ":" + _second);
_countdown--;
editCookie("xxxx", _countdown * 1000, _countdown * 1000);
}
//每1000毫秒执行一次
setTimeout(function() {
settime(remainTime);
}, 1000);
}
//时添加cookie
function addCookie(name, value, expiresHours) {
var cookieString = name + "=" + escape(value); //escape() 函数可对字符串进行编码,这样就可以在所有的计算机上读取该字符串。
//判断是否设置过期时间,0代表关闭浏览器时失效
if (expiresHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000);
cookieString = cookieString + ";expires=" + date.toUTCString();
}
document.cookie = cookieString;
}
//修改cookie的值
function editCookie(name, value, expiresHours) {
var cookieString = name + "=" + escape(value);
if (expiresHours > 0) {
var date = new Date();
date.setTime(date.getTime() + expiresHours * 1000); //单位是毫秒
cookieString = cookieString + ";expires=" + date.toGMTString();
}
document.cookie = cookieString;
}
//根据名字获取cookie的值
function getCookieValue(name) {
var strCookie = document.cookie;
var arrCookie = strCookie.split(";");
for (var i = 0; i < arrCookie.length; i++) {
var arr = arrCookie[i].split("=");
if (arr[0] == name) {
return unescape(arr[1]);
break;
} else {
continue;
}
}
}
</script>
<span id="remainTime"></span>
</body>