当前位置: 首页 > 图文教程 > 网络编程 > Javascript > JS代码实例:实现随机加载不同的CSS样式

Javascript
form中限制文本字节数js代码
use jscript with List Proxy Server Information
use jscript List Installed Software
List Installed Software Features
List Information About the Binary Files Used by an Application
List the Codec Files on a Computer
List the UTC Time on a Computer
List Installed Hot Fixes
excel操作之Add Data to a Spreadsheet Cell
Add Formatted Data to a Spreadsheet
Apply an AutoFormat to an Excel Spreadsheet
JavaScript语法着色引擎(demo及打包文件下载)
类之Prototype.js学习
一款JavaScript压缩工具:X2JSCompactor
iis6+javascript Add an Extension File
jscript之Open an Excel Spreadsheet
jscript之Read an Excel Spreadsheet
jscript之List Excel Color Values
去除图像或链接黑眼圈的两种方法总结
Add a Formatted Table to a Word Document

Javascript 中的 JS代码实例:实现随机加载不同的CSS样式


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2010-01-03   浏览: 352 ::
收藏到网摘: n/a

随机载入CSS样式的JS效果实际上很好实现,本文的代码如下,具体思路是用一个默认的CSS样式:default.css。另外再用三个其他名称的CSS:skin1.css,skin2.css,skin3.css。当然你可以用更多的样式表,随后在载入时进行随机替换,因为最先载入的default.css样式是直接写在页面上,而JS随机载入的后面CSS文件会覆盖之前的CSS,只要CSS中的元素名称相同即可。

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, "/", "websbook.com", false);
 
//若样式名称不为"default"默认样式,则向<head />标签中写入定制样式
                if(currentStyle != "default")
{
document.write('<link rel="stylesheet" type="text/css"
                  href="'
+ this.baseSkinUrl + this.styles[random] + '.css" />');
}
}
}
 
Init.loadCSS();