JS代碼執行個體:實現隨機載入不同的CSS樣式

來源:互聯網
上載者:User

如果讓網頁瀏覽者每次開啟頁面都有新的感覺,可以通過替換css樣式來處理。下面來介紹一下。

隨機載入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();

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.