萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JavaScript 實現隨機載入 CSS 樣式表:預設樣式 + 動態覆蓋機制

隨機切換網站視覺風格可增加用戶新鮮感。本文實作一套「預設樣式 + 隨機主題樣式覆蓋」機制,利用 Cookie 記錄上次風格避免連續重複,支援多主題擴展。

核心原理

  1. HTML 靜態引入 default.css 作為基礎樣式
  2. JS 執行時隨機選擇一個主題樣式 (如 skin1.css)
  3. 動態建立 <link> 標籤插入 <head>,後載入樣式因優先權相同、順序靠後而覆蓋預設值
  4. Cookie 記錄本次選擇,下次隨機時排除相同風格

完整實作代碼 (模組化寫法)

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();

部署步驟

  1. 準備 CSS 檔案:default.css (基礎)、skin1.css、skin2.css... 放入 /blog/css/skin/
  2. HTML <head> 中靜態引入預設樣式:
    <link rel="stylesheet" href="/blog/css/skin/default.css" />
  3. 在 <head> 結束前或 <body> 開頭引入/內嵌上述 JS 並呼叫 ThemeLoader.loadCSS()

進階擴充建議

  • 主題切換按鈕:提供 UI 讓用戶手動選擇,呼叫 setCookie + 重新載入頁面或動態切換 <link> 的 href
  • 權重隨機:為熱門主題設定較高權重
  • LocalStorage 替代 Cookie:避免每請求攜帶 Cookie,節省頻寬
  • CSS 變數 (Custom Properties):現代瀏覽器可僅切換色彩變數,無需整份 CSS 覆蓋
注意:document.write 僅在文檔解析階段有效。若需 AJAX 載入後動態切換,請改用 document.createElement('link') + head.appendChild()。
copyright © 萬盛學電腦網 all rights reserved