两种让用户自定义项目主题色的方案

2次阅读

共计 2289 个字符,预计需要花费 6 分钟才能阅读完成。

前言
大家应该见过不少可以更换主题或主题颜色的网站,如果是更换内置的几套方案可以直接通过简单的替换 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’);
}
如果大家还有什么比较好的方案也希望留言多多分享

正文完
 0