web 添加主题样式注册到root伪类
注册和使用
注册:
:root{ --sansi-theme-c1: red;}
使用
.bgView{ background: var(--sansi-theme-c1, red) }
动态注册和修改
state.currentTheme = theme
const cssRule = document.styleSheets[0].cssRules[0]
// 判断第一个样式表的第一条规则是否存在,防止和饿了么的注册存在冲突
const isExist = cssRule['selectorText'] === ':root' && cssRule['cssText'].indexOf('--sansi-theme') > -1
if (isExist) document.styleSheets[0].deleteRule(0)
let views = state.currentTheme.views
// 动态修改主题
let styleString :string = ''
Object.keys(views).forEach((key)=>{
Object.keys(views[key]).forEach((key1)=>{
const str = `--sansi-theme-${key}-${key1}:` + (views[key][key1].value || `var(--sansi-theme-${views[key][key1]?.default})`) + ';'
styleString += str
})
})
const themeRule = `:root{
--sansi-theme-c1: ${state.currentTheme.colors.c1.value};
--sansi-theme-c2: ${state.currentTheme.colors.c2.value};
--sansi-theme-c3: ${state.currentTheme.colors.c3.value};
--sansi-theme-c4: ${state.currentTheme.colors.c4.value};
--sansi-theme-c5: ${state.currentTheme.colors.c5.value};
--sansi-theme-c6: ${state.currentTheme.colors.c6.value};
--sansi-theme-c7: ${state.currentTheme.colors.c7.value};
--sansi-theme-c8: ${state.currentTheme.colors.c8.value};
--sansi-theme-c9: ${state.currentTheme.colors.c9.value};
${styleString}
}
`
document.styleSheets[0].insertRule(themeRule, 0)
效果
将样式注册到root伪类中,全局使用var(--sansi-theme-c1)
即可设置样式