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

如何使用CSSStyleSheet.insertRule()修改:root伪类的CSS变量属性

核心实现逻辑

你原有写法是给根元素设置行内CSS变量,仅对当前页面生效,页面刷新/跳转后会失效。搭配CSSStyleSheet.insertRule()+本地存储即可实现全站共用样式表下的持久生效,解决跳转后hash丢失的问题。

完整实现代码

// 优先读取当前URL的hash,无hash则读取本地存储的历史配置
const targetColor = window.location.hash || localStorage.getItem('siteMainBgColor')

if (targetColor) {
  // 把颜色值存入本地存储,跨页面跳转后仍可读取
  localStorage.setItem('siteMainBgColor', targetColor)

  // 方式1:插入到你全站共用的外联样式表,索引对应你公共样式表的位置,默认第一个外联样式表索引为0
  const commonStyleSheet = document.styleSheets[0]
  // 第二个参数为插入位置,0代表插入到样式表最顶部,后续同权重规则可覆盖它
  commonStyleSheet.insertRule(`:root { --main-bg-color: ${targetColor} }`, 0)

  // 方式2:如果公共样式表跨域无法操作,可手动新建样式标签插入规则
  // const customStyle = document.createElement('style')
  // document.head.appendChild(customStyle)
  // customStyle.sheet.insertRule(`:root { --main-bg-color: ${targetColor} }`, 0)
}

后续更新颜色的方法

需要动态修改背景色时调用下面的方法即可,会自动更新规则和本地存储:

function updateMainBgColor(newColor) {
  localStorage.setItem('siteMainBgColor', newColor)
  const commonStyleSheet = document.styleSheets[0]
  // 先删除之前插入的旧规则,避免规则重复
  commonStyleSheet.deleteRule(0)
  // 插入新的颜色规则
  commonStyleSheet.insertRule(`:root { --main-bg-color: ${newColor} }`, 0)
}

注意事项

  • 如果你选择插入的是跨域外联样式表,浏览器会因同源策略禁止读写,优先选择同域公共样式表或者用手动新建style标签的方式
  • 插入规则的索引不能超过样式表现有规则的总长度,否则会抛出报错,可通过commonStyleSheet.cssRules.length获取当前规则总数调整插入位置

内容的提问来源于stack exchange,提问作者Blue Moon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:24:01