隨機切換網站視覺風格可增加用戶新鮮感。本文實作一套「預設樣式 + 隨機主題樣式覆蓋」機制,利用 Cookie 記錄上次風格避免連續重複,支援多主題擴展。
default.css 作為基礎樣式skin1.css)<link> 標籤插入 <head>,後載入樣式因優先權相同、順序靠後而覆蓋預設值var ThemeLoader = {
// 設定區
baseSkinUrl: '/blog/css/skin/', // 樣式表目錄
styles: ['default', 'skin1', 'skin2', 'skin3'], // 檔名不含副檔名
cookieKey: 'css9_blog_random_css', // Cookie 鍵名
cookieDomain: 'websbook.com', // Cookie 域
cookiePath: '/', // Cookie 路徑
cookieHours: 24, // 有效期 (小時)
// 工具方法
getRandomNum: function(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
},
getCookie: function(name) {
var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]*)(;|$)'));
return match ? unescape(match[2]) : null;
},
setCookie: function(name, value, hours, path, domain, secure) {
var cookie = name + '=' + encodeURIComponent(value);
if (hours) {
var date = new Date();
date.setTime(date.getTime() + hours * 3600 * 1000);
cookie += ';expires=' + date.toGMTString();
}
if (path) cookie += ';path=' + path;
if (domain) cookie += ';domain=' + domain;
if (secure) cookie += ';secure';
document.cookie = cookie;
},
// 核心邏輯
loadCSS: function() {
var len = this.styles.length;
var random = this.getRandomNum(0, len - 1);
var lastStyle = this.getCookie(this.cookieKey);
var currentStyle = this.styles[random];
// 避免連續相同風格
while (currentStyle === lastStyle) {
random = this.getRandomNum(0, len - 1);
currentStyle = this.styles[random];
}
// 寫入 Cookie
this.setCookie(this.cookieKey, currentStyle, this.cookieHours,
this.cookiePath, this.cookieDomain, false);
// 非預設風格才動態載入 (default.css 已在 HTML 靜態引入)
if (currentStyle !== 'default') {
document.write(
'<link rel="stylesheet" type="text/css" ' +
'href="' + this.baseSkinUrl + currentStyle + '.css" />'
);
}
}
};
// 頁面載入時立即執行 (需在 <head> 結束前或 <body> 開頭調用)
ThemeLoader.loadCSS();
default.css (基礎)、skin1.css、skin2.css... 放入 /blog/css/skin/<head> 中靜態引入預設樣式:<link rel="stylesheet" href="/blog/css/skin/default.css" /><head> 結束前或 <body> 開頭引入/內嵌上述 JS 並呼叫 ThemeLoader.loadCSS()setCookie + 重新載入頁面或動態切換 <link> 的 href注意:document.write僅在文檔解析階段有效。若需 AJAX 載入後動態切換,請改用document.createElement('link')+head.appendChild()。