在HTML的body标签上先定义一个id元素属性
<body id="sm-theme"> <sj-root></sj-root></body>
css定义css变量,变量的定义必须要以 -- 开头
#sm-theme { --smTheme: #2A2A2A; --smSettingRight: #484848; --smSettingRightBox: #2A2A2A;}
在任何地方使用js/ts来获取body上定义的sm-theme属性名从而操作定义在里面的css样式变量
changeTheme(colorName) { const theamEle = document.getElementById('sm-theme'); // 获取id为sm-theme的元素 theamEle.style.setProperty('--smTheme', colorName); // 设置--smTheme变量为我们想要的颜色 const theamColor = getComputedStyle(theamEle).getPropertyValue('--smTheme'); // 获取--smTheme变量的颜色 if (theamColor === '#2A2A2A') { theamEle.style.setProperty('--smSettingRight', '#484848'); theamEle.style.setProperty('--smSettingRightBox', '#2A2A2A'); } else { theamEle.style.setProperty('--smSettingRight', 'rgba(180,180,180,0.4)'); theamEle.style.setProperty('--smSettingRightBox', '#5C5C5C'); }