在上一篇文章中曾提到要给自己的微博客制作多个样式,然后用户每次访问时随机载入样式,让微博在视觉上保持新鲜感。虽然思路与实现都比较简单,但还是想记录下来,与大家分享。
【明确需求】
【实现思路】
【实现代码】
比较简单,我这里就直接贴代码了,里面略加注释:
var Init = { //样式表文件目录路径 baseSkinUrl : "/blog/css/skin/", //样式表文件名称列表 styles : ["default", "skin1", "skin2", "skin3"], //样式cookie的key值 cookieKey : "css9_blog_random_css", //定义方法,获取min至max间的随机数,包含min及max getRandomNum : function(min, max){ return min + Math.floor(Math.random() * (max - min + 1)); }, //定义方法,获取cookie值 getCookie : function(name) { var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null) { return unescape(arr[2]); } return null; }, //定义方法,设置cookie值 setCookie : function(sName,sValue,objHours,sPath,sDomain,bSecure){ var sCookie = sName + "=" + encodeURIComponent(sValue); if (objHours) { var date = new Date(); var ms = objHours * 3600 * 1000; date.setTime(date.getTime() + ms); sCookie += ";expires=" + date.toGMTString(); } if (sPath) { sCookie += ";path=" + sPath; } if (sDomain) { sCookie += ";domain=" + sDomain; } if (bSecure) { sCookie += ";secure"; } document.cookie=sCookie; }, //定义方法,通过获取随机数随机加载CSS loadCSS : function(){ var length = this.styles.length, random = this.getRandomNum(0, length-1), cookieStyle = this.getCookie(this.cookieKey), currentStyle = "default"; //如果当前随机取到的样式与cookie中样式相同,则重新计算随机数 while(this.styles[random] == cookieStyle) { random = this.getRandomNum(0, length-1) } currentStyle = this.styles[random]; //将新样式存入cookie,cookie有效时间为24小时 this.setCookie(this.cookieKey, currentStyle, 24, "/", "css9.net", false); //若样式名称不为"default"默认样式,则向<head />标签中写入定制样式 if(currentStyle != "default") { document.write('<link rel="stylesheet" type="text/css" href="' + this.baseSkinUrl + this.styles[random] + '.css" />'); } } } Init.loadCSS(); //执行随机加载CSS方法
将上面js代码保存为Init.js文件,并在<head />中加载该js文件。
【查看效果】
可以去我的微博客查看效果,多次刷新效果更好呦 。现在只有三种样式,以后会逐渐添加更多样式。
提示: 如果你的网页中已经使用了jquery,那么可以用我之前介绍的jQuery cookie操作插件实现cookie的读写操作,不必再定义代码中的setCookie和getCookie方法。