javascript中如何操作CSS变量?_javascript如何动态改变主题样式?

JavaScript通过style.setProperty()和getComputedStyle().getPropertyValue()操作CSS自定义属性实现动态主题切换,推荐挂载于:root并配合class切换与localStorage持久化。

JavaScript 可以通过 style.setProperty()getComputedStyle().getPropertyValue() 直接读写 CSS 自定义属性(即 CSS 变量),这是实现动态主题切换最轻量、最推荐的方式。

设置 CSS 变量(修改主题色、字体等)

把变量挂载在 :root 上,就能全局生效。JS 中用 document.documentElement.style 操作:

  • 设置单个变量:document.documentElement.style.setProperty('--primary-color', '#4a6fa5');
  • 批量设置(适合主题对象):
    const theme = { '--primary-color': '#ff6b6b', '--bg-color': '#f8f9fa', '--text-color': '#333' };
    Object.entries(theme).forEach(([prop, val]) => {
      document.documentElement.style.setProperty(prop, val);
    });
  • 注意变量名要带两个短横线前缀(--),且大小写敏感。

读取 CSS 变量(获取当前主题值)

getComputedStyle:root 获取,返回的是计算后的字符串(含单位):

  • 基础读取:const color = getComputedStyle(document.documentElement).getPropertyValue('--primary-color').trim(); // → "#4a6fa5"
  • 读取后可做逻辑判断,比如判断当前是否为深色模式:if (color === '#1a1a1a') { /* 深色主题逻辑 */ }
  • 注意:未定义的变量会返回空字符串,建议加默认回退处理。

配合 class 切换实现多主题预设

不推荐纯 JS 写死所有变量,更优雅的方式是预定义几套主题 class,在 CSS 中声明对应变量,JS 只负责切 class:

  • CSS 中:
    :root { --primary-color: #007bff; }
    .theme-dark { --primary-color: #0056b3; --bg-color: #212529; }
    .theme-high-contrast { --primary-color: #e60000; }
  • JS 切换:document.documentElement.className = 'theme-dark';document.documentElement.classList.toggle('theme-dark');
  • 优势:样式集中管理、支持 CSS 过渡动画、便于维护和扩展。

持久化主题选择(刷新不丢失)

把用户偏好存到 localStorage,页面加载时恢复:

  • 保存:localStorage.setItem('theme', 'theme-dark');
  • 始化时读取并应用:
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme && document.body.classList.contains(savedTheme)) {
      document.documentElement.className = savedTheme;
    }
  • 也可监听系统级深色模式(prefers-color-scheme)作为默认 fallback。

基本上就这些。核心就三点:变量定义在 :root、JS 用 setProperty/getPropertyValue 操作、搭配 class + localStorage 做工程化管理。不复杂但容易忽略细节,比如变量名格式、trim 空格、CSS 作用域范围等。