更换主题颜色
- 把 css 文件放到服务器上,通过 XMLHttpRequest 请求文件,获取到文件内容之后替换颜色。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30getFile(url: string) {
return new Promise((resolve, reject) => {
const client = new XMLHttpRequest();
client.open("GET", url);
client.responseType = "text";
client.onreadystatechange = () => {
if (client.readyState !== 4) {
return;
}
if (client.status === 200) {
const urlArr = client.responseURL.split("/");
resolve({
data: client.response,
url: urlArr[urlArr.length - 1],
});
} else {
reject(new Error(client.statusText));
}
};
client.send();
});
}
getIndexStyle() {
this.getFile("//doc.mamaezhan.com/web/my_theme.css")
.then(({data}: any) => {
this.originalStyle = this.getStyleTemplate(data);
this.writeNewStyle();
});
} - 通过 getStyleTemplate 方法,把要更改的颜色替换成临时变量字段,如”#001528”颜色先替换成”primary”字段
1
2
3
4
5
6
7
8
9
10
11
getStyleTemplate(data: any) {
const colorMap: any = {
"#001528": "primary",
};
Object.keys(colorMap).forEach((key) => {
const value = colorMap[key];
data = data.replace(new RegExp(key, "ig"), value);
});
return data;
} - 再定义一个颜色变量,为需要替换的新颜色。把替换的变量字段最终替换成新的颜色
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19const colors: any = {
primary: "#001528",
};
writeNewStyle() {
let cssText = this.originalStyle;
Object.keys(this.colors).forEach((key) => {
cssText = cssText.replace(new RegExp("(:|\\s+)" + key, "g"), "$1" + this.colors[key]);
});
if (this.originalStylesheetCount === document.styleSheets.length) {
const style = document.createElement("style");
style.innerText = cssText;
document.head.appendChild(style);
} else {
const lastChild: any = document.head.lastChild;
lastChild.innerText = cssText;
}
}
本站点所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 吕钒的后花园!