你們應該見過很多能夠更換主題或主題顏色的網站,若是是更換內置的幾套方案能夠直接經過簡單的替換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