JS网页换肤读取cookie基础案例

JS网页换肤读取cookie基础案例

功能简介: 页面加载时判断cookie是否存在存在就读取cookie,点击换肤按钮添加(更换)CSS文件并把文件名存入cookie;

本文Cooke相关资料来源

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附加不同颜色的文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值