如何让JavaScript切换的CSS主题在页面刷新后保持生效?
刷新页面后保持主题设置的解决方案
问题描述
我有一个包含light.css(浅色主题)和dark.css(深色主题)两个CSS文件的HTML页面,点击对应按钮可切换至对应的主题样式。但当前切换为深色主题后,刷新页面会恢复为浅色主题,请问该如何实现刷新后保持已设置的主题?
当前使用的主题切换代码:
function toggleTheme() { // Obtains an array of all <link> // elements. // Select your element using indexing. var theme = document.getElementsByTagName("link")[0]; // Change the value of href attribute // to change the css sheet. if (theme.getAttribute("href") == "light.css") { theme.setAttribute("href", "dark.css"); } else { theme.setAttribute("href", "light.css"); } }
解决方法
核心思路是利用浏览器的localStorage本地存储API,把用户选择的主题保存下来,页面加载时再读取并应用。
1. 修改主题切换函数,添加存储逻辑
每次切换主题后,将当前选择的主题路径存入localStorage:
function toggleTheme() { var theme = document.getElementsByTagName("link")[0]; let newTheme; if (theme.getAttribute("href") === "light.css") { newTheme = "dark.css"; } else { newTheme = "light.css"; } theme.setAttribute("href", newTheme); // 保存主题到本地存储 localStorage.setItem("selectedTheme", newTheme); }
2. 页面加载时读取存储并应用主题
在页面加载完成后,读取localStorage中保存的主题,如果没有保存过则默认使用浅色主题:
// 页面初始化时应用保存的主题 window.addEventListener("load", function() { var theme = document.getElementsByTagName("link")[0]; // 获取保存的主题,默认值为light.css var savedTheme = localStorage.getItem("selectedTheme") || "light.css"; theme.setAttribute("href", savedTheme); });
说明
localStorage是浏览器提供的持久化存储方案,数据会一直保留在用户浏览器中,除非用户手动清除浏览器缓存或调用localStorage.removeItem方法删除对应项,因此刷新页面后依然能读取到之前设置的主题。
内容的提问来源于stack exchange,提问作者Skittlq
相关产品推荐
相关产品推荐

