JS网页换肤读取cookie基础案例
功能简介: 页面加载时判断cookie是否存在存在就读取cookie,点击换肤按钮添加(更换)CSS文件并把文件名存入cookie;
HTML部分:
<a href="javascript:void(0)" id="blue" onclick="bgcolor('blue.css',this)">blue</a>
<a href="javascript:void(0)" id="orange" onclick="bgcolor('orange.css',this)">orange</a>
<a href="javascript:void(0)" id="red" onclick="bgcolor('red.css',this)">red</a>
JS部分:
function setCookie(name, val) { //写入coolie
var Days = 30 * 12; //cookie 将被保存一年
var exp = new Date(); //获得当前时间
exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000); //换成毫秒
document.cookie = name + "=" + escape(val) + ";expires=" + exp.toGMTString(); //escape()转码 toGMTString()把Date 对象转换为字符串,并返回结果。
}
function getCookie(name) { //读取cookie
var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
if(arr != null) {
return unescape(arr[2]);
} else {
return null;
}
}
function bgcolor(file, $this) {//点击换肤按钮换色并把文件名存入cookie
var skinid = document.getElementById("skin");
if($this.getAttribute("id") == "blue") {
skinid.href = "css/" + file;
setCookie("colors", file);
//if() skinid.href
} else if($this.getAttribute("id") == "orange") {
skinid.href = "css/" + file;
setCookie("colors", file);
} else if($this.getAttribute("id") == "red") {
skinid.href = "css/" + file;
setCookie("colors", file);
}
}
function loadfile() { //加载时读取缓存看缓存有没有存上次的信息
var skinid = document.getElementById("skin");
if(getCookie("colors") != null) {
skinid.href = "css/" + getCookie("colors");
}
}
CSS部分是3个给body附加不同颜色的文件