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

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

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理