若希望網頁每次重新整理時,都能呈現不同的視覺風格,可以透過 JavaScript 動態載入不同的 CSS 檔案。核心概念很簡單:先準備多組樣式,再隨機挑選一組套用;若希望避免連續兩次相同,可利用 Cookie 或 localStorage 記錄上次選擇。
以下範例使用原生 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 的路徑與有效期限要符合預期。
此外,若樣式切換會影響版面可讀性,建議提供使用者可理解的主題名稱,或加入切換提示,讓視覺變化不只是隨機驚喜,也能成為整體體驗的一部分。