前言大家应该见过不少可以更换主题或主题颜色的网站,如果是更换内置的几套方案可以直接通过简单的替换css文件来实现,我们就不说了;本文就介绍一种用户自定义替换的主题题色的简单方案!1. 相关知识点1.1 CSSStyleSheet.insertRule()CSSStyleSheet.insertRule(rule, index);参数:rule: string,包含要插入的样式规则index: number, 插入的位置, 可选,默认:0document.styleSheets[0].insertRule(’.selector {color: red}’, 0);1.2 CSSStyleSheet.addRule()CSSStyleSheet.addRule(selector, cssText, index)参数:selector: string,选择器文本rule: string,包含要插入的样式规则index: number, 插入的位置, 可选,默认:length - 1document.styleSheets[0].addRule(’.selector’, ‘color: red’, 0);关于insertRule与addRule的区别addRule是IE专用的方法传参略有不同,并且insertRule默认将样式规则添加到css的第一条,而addRule默认添加到最后一条。补充说明:虽说addRule是IE的方法,但是目前chrome等主流方法也都支持,可以放心的使用;而另一方面insertRule也支持IE9及以上。1.3 CSS3变量可以让我们像Sass、Less那样创建变量;:root{ –color: pink;}div{ color: var(–color);}.content{ –red: red; –string: ‘支持字符串’; –中文名: 20; background-color: var(–red);}遗憾的是目前不支持IE,不过可以用JS来判断varisSupported = window.CSS && window.CSS.supports && window.CSS.supports(’–a’, 0);if (isSupported) { /* supported /} else { / not supported */}更多关于css3变量: 请点这里2. 具体方案2.1 通过insertRule/addRule 实现 function setTheme(color){ let link = document.createElement(“style”); let head = document.getElementsByTagName(“head”)[0]; //设置主题色时现将原先的样式文件移除,虽然样式之间可以覆盖,但为了避免添加过多,还是清一下。 document.getElementById(’theme’) && head.removeChild(document.getElementById(’theme’)); link.rel = “stylesheet”; link.type = “text/css”; link.id = “theme”; head.appendChild(link); let themeData = { color: color, }; let len = document.styleSheets.length - 1; //进行本地存储 localStorage.setItem(‘Theme’, JSON.stringify(themeData)); document.styleSheets[len].addRule(’.T-BG’, background-color: ${this.color} !important
); document.styleSheets[len].addRule(’.T-FT’, color: ${color} !important
); document.styleSheets[len].addRule(’.T-FT-H:hover’, color: ${color} !important
); document.styleSheets[len].addRule(’.T-BD’, border-color: ${color} !important
); document.styleSheets[len].addRule(’.T-SD’, box-shadow: 0 0 5px 1px ${color} !important
); document.styleSheets[len].addRule(’.T-SD-H:hover’, box-shadow: 0 0 5px 1px ${color} !important
); document.styleSheets[len].addRule(’.T-TSD-H:hover’, text-shadow: 0 0 5px ${color} !important
); document.styleSheets[len].addRule(’.T-TSD’, text-shadow: 0 0 5px ${color} !important
); }2.1 通过css3变量 实现 //这个方法就简单很多,不过开发前请先了解其兼容性,开发时主题色相关颜色直接调用变量,就像大家平时用Sass一样。 function setTheme(color){ // 设置变量, document.body.style.setProperty(’–ThemeColor’, ‘red’); }如果大家还有什么比较好的方案也希望留言多多分享