The JS effect of randomly loading CSS styles is actually very good. The code in this article is as follows. The specific idea is to use a default CSS style: default.css. In addition, three other names of CSS are used: skin1.css, skin2.css, and skin3.css. Of course, you can use more style sheets, and then randomly replace them when loading, because the default.css style that is loaded first is written directly in
The JS effect of randomly loading CSS styles is actually very good. The code in this article is as follows. The specific idea is to use a default CSS style: default.css. In addition, three other names of CSS are used: skin1.css, skin2.css, and skin3.css. Of course, you can use more style sheets, and then randomly replace them when loading, because the default.css style that is loaded first is written directly on the page, and the later CSS file randomly loaded by JS will overwrite the previous CSS. , As long as the element names in the CSS are the same.
var Init = {
// stylesheet file directory path
baseSkinUrl: "/ blog / css / skin /",
// style sheet file name list
styles: ["default", "skin1", "skin2", "skin3"],
// key value of style cookie
cookieKey: "css9_blog_random_css",
// Define the method to get a random number between min and max, including min and max
getRandomNum: function (min, max) {
return min + Math.floor (Math.random () * (max-min + 1));
},
// Define method to get cookie value
getCookie: function (name) {
var arr = document.cookie.match (new RegExp ("(^ |)" + name + "= ([^;] *) (; | $)"));
if (arr! = null) {
return unescape (arr [2]);
}
return null;
},
// define method, set cookie value
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;
},
// Define method to load CSS randomly by getting random numbers
loadCSS: function () {
var length = this.styles.length,
random = this.getRandomNum (0, length-1),
cookieStyle = this.getCookie (this.cookieKey),
currentStyle = "default";
// If the currently randomly obtained style is the same as the style in the cookie, recalculate the random number
while (this.styles [random] == cookieStyle)
{
random = this.getRandomNum (0, length-1)
}
currentStyle = this.styles [random];
// Save the new style in the cookie, the cookie is valid for 24 hours
this.setCookie (this.cookieKey, currentStyle, 24, "/", "websbook.com", false);
// If the style name is not "default", write a custom style to the <head /> tag
if (currentStyle! = "default")
{
document.write ('<link rel = "stylesheet" type = "text / css"
href = "'+ this.baseSkinUrl + this.styles [random] +' .css" /> ');
}
}
}
Init.loadCSS ();