如何利用localStorage实现页面刷新后仍保留样式效果?
实现页面刷新后保留样式效果
要让样式在页面刷新后仍然保留,我们可以利用浏览器的localStorage存储用户选择的颜色值,再在页面加载时读取该值并应用到样式中。以下是修改后的完整代码及说明:
修改后的JS代码
document.addEventListener("DOMContentLoaded", () => { const buttons = document.querySelectorAll(".btn"); const root = document.querySelector(":root"); // 页面加载时读取本地存储的颜色并应用 const savedColor = localStorage.getItem("selectedPrimaryColor"); if (savedColor) { root.style.setProperty("--bs-primary-rgb", savedColor); // 标记选中的按钮(可选) const activeBtn = document.querySelector(`.btn[data-color="${savedColor}"]`); activeBtn?.classList.add("active"); } buttons.forEach((btn) => { btn.style.backgroundColor = btn.getAttribute("data-color"); btn.addEventListener("click", () => { const selectedColor = btn.getAttribute("data-color"); root.style.setProperty("--bs-primary-rgb", selectedColor); // 将选中颜色存入本地存储 localStorage.setItem("selectedPrimaryColor", selectedColor); // 更新按钮选中状态(可选) buttons.forEach(b => b.classList.remove("active")); btn.classList.add("active"); }); }); });
关键改动说明
- 存储选中颜色:用户点击按钮时,通过
localStorage.setItem()将选中的data-color值保存到浏览器本地存储,数据会持久保留直至手动清除。 - 页面加载恢复样式:在
DOMContentLoaded事件中,通过localStorage.getItem()读取保存的颜色值,若存在则直接设置为根元素的--bs-primary-rgb变量。 - 按钮状态标记(可选):添加
active类标记当前选中的按钮,需在CSS中定义.active样式(如边框、阴影),让用户直观看到选择状态。
内容的提问来源于stack exchange,提问作者Angus dev
相关产品推荐
相关产品推荐

