兩種讓使用者自定義專案主題色的方案
前言
大家應該見過不少可以更換主題或主題顏色的網站,如果是更換內建的幾套方案可以直接通過簡單的替換css檔案來實現,我們就不說了;本文就介紹一種使用者自定義替換的主題題色的簡單方案!
1. 相關知識點
1.1 CSSStyleSheet.insertRule()
CSSStyleSheet.insertRule(rule, index);
引數:
- rule: string,包含要插入的樣式規則
- index: number, 插入的位置, 可選,預設:0
document.styleSheets[0].insertRule('.selector {color: red}', 0);
1.2 CSSStyleSheet.addRule()
CSSStyleSheet.addRule(selector, cssText, index)
引數:
- selector: string,選擇器文字
- rule: string,包含要插入的樣式規則
- index: number, 插入的位置, 可選,預設:length - 1
document.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'); }
如果大家還有什麼比較好的方案也希望留言多多分享