如何将网站深色模式与语言设置存储至Cookie以保留配置
要让语言切换、深色模式的设置在页面刷新/站内跳转后保留,核心是修改现有代码,在切换设置时写入Cookie,并在页面加载时读取Cookie恢复状态。
第一步:添加Cookie操作工具函数
先写两个通用函数简化Cookie读写,确保全站页面都能访问到这些配置:
// 设置Cookie,默认有效期7天,path=/确保全站生效 function setCookie(name, value, days = 7) { const date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); const expires = "expires=" + date.toUTCString(); document.cookie = `${name}=${value}; ${expires}; path=/`; } // 根据名称获取Cookie值 function getCookie(name) { const nameEQ = `${name}=`; const cookieList = document.cookie.split(';'); for(let i = 0; i < cookieList.length; i++) { let cookie = cookieList[i]; while (cookie.charAt(0) === ' ') cookie = cookie.substring(1); if (cookie.indexOf(nameEQ) === 0) return cookie.substring(nameEQ.length); } return null; }
第二步:修改语言切换代码
页面加载时读取Cookie恢复语言设置,切换时写入Cookie:
const langEl = [...document.querySelectorAll(".lang")]; let chosenLanguage = 'NL'; // 页面加载时恢复Cookie中的语言配置 window.addEventListener('load', () => { const savedLang = getCookie('userLanguage'); if (savedLang) { const targetLang = langEl.find(el => el.getAttribute('language') === savedLang); if (targetLang) { // 同步选中状态和语言值 langEl.forEach(item => item.classList.remove('active')); targetLang.classList.add('active'); chosenLanguage = targetLang.innerText; search(); // 触发语言切换后的原有逻辑 } } }); langEl.forEach((el) => { el.addEventListener("click", () => { langEl.forEach(item => item.classList.remove("active")); el.classList.add("active"); chosenLanguage = el.innerText; const langAttr = el.getAttribute("language"); search(); // 将选中的语言存入Cookie setCookie('userLanguage', langAttr); }); });
- 用
language属性值存Cookie比存文本更稳定,避免文本修改导致配置失效 - 页面加载时优先读取Cookie配置,覆盖默认值
第三步:修改深色模式代码
同样在页面加载时恢复状态,切换时写入Cookie:
var icon = document.getElementById("icon"); // 页面加载时恢复Cookie中的深色模式配置 window.addEventListener('load', () => { const isDarkMode = getCookie('darkMode') === 'true'; if (isDarkMode) { document.body.classList.add("dark-theme"); icon.src = "images/sun.png"; } else { document.body.classList.remove("dark-theme"); icon.src = "images/moon.png"; } }); icon.onclick = function() { document.body.classList.toggle("dark-theme"); const isDark = document.body.classList.contains("dark-theme"); // 更新图标 icon.src = isDark ? "images/sun.png" : "images/moon.png"; // 将深色模式状态存入Cookie(Cookie仅支持字符串,所以转成字符串存储) setCookie('darkMode', isDark.toString()); };
注意事项
- 若需要更长的有效期,可调整
setCookie的days参数(比如设为365表示一年) - 用户清除浏览器Cookie后,配置会恢复默认值,属于正常行为
内容的提问来源于stack exchange,提问作者Pascal
相关产品推荐
相关产品推荐

