DIV CSS 佈局教程網

每次載入隨機切換 CSS:讓網頁保持視覺新鮮感
編輯:關於JavaScript     

讓每次載入都有新鮮感

若希望網頁每次重新整理時,都能呈現不同的視覺風格,可以透過 JavaScript 動態載入不同的 CSS 檔案。核心概念很簡單:先準備多組樣式,再隨機挑選一組套用;若希望避免連續兩次相同,可利用 Cookie 或 localStorage 記錄上次選擇。

需求拆解

  • 預設樣式:default.css 提供基本外觀。
  • 自訂樣式:skin1.css、skin2.css、skin3.css 提供不同主題。
  • 隨機規則:每次載入時隨機選擇其中一種。
  • 避免重複:盡量讓這次樣式與上次不同。

實作思路

  1. 定義樣式名稱清單。
  2. 讀取上次使用的樣式。
  3. 隨機產生這次要使用的樣式。
  4. 若與上次相同,可重新隨機或改成輪替。
  5. 動態建立 link 元素並插入 head。
  6. 將本次樣式寫入 Cookie,供下次判斷。

以下範例使用原生 JavaScript,適合不想額外引入函式庫的情境:

const styleList = ['default', 'skin1', 'skin2', 'skin3'];
const cookieKey = 'random_css';

function getCookie(name) {
  const match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
  return match ? decodeURIComponent(match[2]) : null;
}

function setCookie(name, value, hours) {
  const expires = new Date(Date.now() + hours * 60 * 60 * 1000).toUTCString();
  document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + expires + '; path=/';
}

function loadRandomStyle() {
  const last = getCookie(cookieKey);
  let current = styleList[Math.floor(Math.random() * styleList.length)];

  while (styleList.length > 1 && current === last) {
    current = styleList[Math.floor(Math.random() * styleList.length)];
  }

  if (current !== 'default') {
    const link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = '/blog/css/skin/' + current + '.css';
    document.head.appendChild(link);
  }

  setCookie(cookieKey, current, 24);
}

loadRandomStyle();

注意事項

若頁面已有 jQuery,也可使用既有的 Cookie 外掛來簡化讀寫流程。不過,無論使用原生或外掛,重點都在於:樣式清單要清楚、隨機邏輯要避免無限迴圈、Cookie 的路徑與有效期限要符合預期。

此外,若樣式切換會影響版面可讀性,建議提供使用者可理解的主題名稱,或加入切換提示,讓視覺變化不只是隨機驚喜,也能成為整體體驗的一部分。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved