你们应该见过很多能够更换主题或主题颜色的网站,若是是更换内置的几套方案能够直接经过简单的替换css文件来实现,咱们就不说了;本文就介绍一种用户自定义替换的主题题色的简单方案!
CSSStyleSheet.insertRule(rule, index);
参数:css
document.styleSheets[0].insertRule('.selector {color: red}', 0);
CSSStyleSheet.addRule(selector, cssText, index)
参数:html
document.styleSheets[0].addRule('.selector', 'color: red', 0);
关于insertRule与addRule的区别css3
补充说明:虽然说addRule是IE的方法,可是目前chrome等主流方法也都支持,能够放心的使用;而另外一方面insertRule也支持IE9及以上。chrome
可让咱们像Sass、Less那样建立变量;app
: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变量: 请点这里this
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`); }
//这个方法就简单不少,不过开发前请先了解其兼容性,开发时主题色相关颜色直接调用变量,就像你们平时用Sass同样。 function setTheme(color){ // 设置变量, document.body.style.setProperty('--ThemeColor', 'red'); }
若是你们还有什么比较好的方案也但愿留言多多分享spa