直接将主题变量对象存入 LocalStorage 即可,关键在于用 JSON.stringify 序列化后存储、JSON.parse 反序列化后遍历设置 CSS 自定义属性,并通过封装 updateTheme 函数统一处理更新与持久化,兼顾默认兜底、类型转换和错误防护。

直接把主题变量对象存进 LocalStorage 即可,关键在于序列化和反序列化,同时注意变量更新后同步写入。
保存主题变量到 LocalStorage
将 CSS 自定义属性(如 --primary-color、--bg-dark)整理成普通 JS 对象,用 JSON.stringify() 转为字符串再存入:
const themeVars = {
'--primary-color': '#3b82f6',
'--bg-dark': '#1e293b',
'--text-light': '#f1f5f9'
};
localStorage.setItem('customTheme', JSON.stringify(themeVars));
从 LocalStorage 恢复并应用到页面
读取后用 JSON.parse() 还原对象,再遍历设置到 document.documentElement.style:
const saved = localStorage.getItem('customTheme');
if (saved) {
const vars = JSON.parse(saved);
Object.entries(vars).forEach(([prop, value]) => {
document.documentElement.style.setProperty(prop, value);
});
}
监听变量变更并自动持久化
封装一个更新函数,每次修改主题时调用,确保 LocalStorage 和页面样式实时一致:
立即学习“Java免费学习笔记(深入)”;
- 避免手动重复调用 setItem,统一入口管理
- 支持单个变量更新(如切换深色模式)或批量覆盖
- 可加简单防错:检查 JSON.stringify 是否失败
function updateTheme(newVars) {
try {
const current = JSON.parse(localStorage.getItem('customTheme') || '{}');
const merged = { ...current, ...newVars };
localStorage.setItem('customTheme', JSON.stringify(merged));
Object.entries(merged).forEach(([prop, value]) => {
document.documentElement.style.setProperty(prop, value);
});
} catch (e) {
console.warn('Theme save failed:', e);
}
}
// 示例:切换深色背景
updateTheme({ '--bg-dark': '#0f172a' });
兼容性与注意事项
LocalStorage 容量约 5–10MB,主题变量极少超限;但需注意:
- 值必须是字符串——数值、布尔、null 都要转成字符串(如 'true'、'12'),否则 CSS 不识别
- 删除变量时,设为空字符串或显式调用 removeProperty,再更新 LocalStorage
- 首次加载时若无缓存,应有默认主题兜底


















