You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 05:10:43