PAYATHON 2026

如何将 :root CSS 变量开关状态保存到 localStorage?

数据小陈

localStorage 写入通常没问题。更常见的是:页面加载时只把存储值写进了 data-crt 属性,却没有同时恢复 :root 的 --crt 变量和 checkbox.checked。点击时又根据 data-crt 翻转,没有读取 checkbox 的勾选状态,结果 UI 和 CSS 变量对不上,看起来就像要点两次才生效。

原因

原代码里 const storedTheme = localStorage.getItem('theme') 只执行了 document.documentElement.setAttribute('data-crt', storedTheme),既没有执行 root.style.setProperty('--crt', 'none') 或 root.style.setProperty('--crt', 'block'),也没有设置 toggle.checked。刷新后 CSS 变量仍是默认的 --crt: block,而 checkbox 的初始勾选状态来自 HTML 的 checked,两者可能都和 localStorage 对不上。点击时 currentTheme 读的是 data-crt 属性,targetTheme 按这个属性翻转,所以第一次点击只是在纠正属性,视觉状态可能没变;第二次点击才真正切到用户想要的状态。

解决步骤

  1. 给 CRT 开关用专用存储键,比如 crt-effect,保存 on 或 off。
  2. 页面加载时读取这个键;没有记录就默认开启,只有明确保存为 off 时才关闭。
  3. 写一个 applyCrt(enabled) 函数,同时设置 checkbox.checked 和 root.style.setProperty('--crt', ...),也可以顺带设置 data-crt 属性。
  4. 把事件从 onclick 改为 change,直接按 toggle.checked 决定状态并写入 localStorage。
  5. 用 try/catch 包住 localStorage 的读写,避免隐私模式或存储被禁用时影响页面切换。

代码示例

:root {
  --crt: block;
}

#pagecontainer::before,
#pagecontainer::after {
  display: var(--crt);
  /* 其他 CRT 样式保持你原来的写法 */
}
<input type='checkbox' id='data-crt' checked>
document.addEventListener('DOMContentLoaded', () => {
  const root = document.documentElement;
  const toggle = document.getElementById('data-crt');
  const STORAGE_KEY = 'crt-effect';

  function applyCrt(enabled) {
    toggle.checked = enabled;
    root.style.setProperty('--crt', enabled ? 'block' : 'none');
    root.setAttribute('data-crt', enabled ? 'crt' : 'nocrt');
  }

  let saved = null;
  try {
    saved = localStorage.getItem(STORAGE_KEY);
  } catch (e) {
    // localStorage 不可用时保持默认开启
  }

  // 首次访问没有记录时默认开启;只有明确保存为 off 才关闭
  const enabled = saved !== 'off';
  applyCrt(enabled);

  toggle.addEventListener('change', () => {
    const enabled = toggle.checked;
    applyCrt(enabled);
    try {
      localStorage.setItem(STORAGE_KEY, enabled ? 'on' : 'off');
    } catch (e) {
      // 写入失败时仍允许本次页面内切换
    }
  });
});

注意事项

  • 如果继续用 data-crt 属性控制样式,CSS 选择器要能覆盖默认值;当前样式用的是 --crt 变量,所以必须设置 root.style.setProperty('--crt', ...)。
  • localStorage 只能存字符串,读取后要自己判断 on/off 或 crt/nocrt。
  • 脚本要放在 DOM 加载后执行,或者用 DOMContentLoaded 包住,否则 getElementById 可能拿到 null。
  • 不要混用 theme 这种过于通用的键,避免和其他主题设置冲突。
  • 如果用户禁用存储,页面仍应能切换,只是刷新后不保留状态。

备注:内容仅供参考。