动态主题
动态主题
动态样式文件
改变皮肤
<link id="skinLink" href="skin-default.css" rel="stylesheet" type="text/css">
换皮肤的时候
skinLink.href = "skin-red.css";
webpack-theme-color-replacer
在
new ThemeColorReplacer({
fileName: "theme-colors-[contenthash:8].css",
matchColors: getAntdSerials("#5d4bff"), // 主色系列
// 改变样式选择器,解决样式覆盖问题
changeSelector(selector) {
switch (selector) {
case ".ant-calendar-today .ant-calendar-date":
return ":not(.ant-calendar-selected-date)" + selector;
case ".ant-btn:focus,.ant-btn:hover":
return ".ant-btn:focus:not(.ant-btn-primary),.ant-btn:hover:not(.ant-btn-primary)";
case ".ant-btn.active,.ant-btn:active":
return ".ant-btn.active:not(.ant-btn-primary),.ant-btn:active:not(.ant-btn-primary)";
default:
return selector;
}
},
});
该插件会生成一个
.el-tag {
color: #f67a17;
}
.el-tag.is-hit {
border-color: #f67a17;
}
并且在
window.__theme_COLOR_cfg = {
url: "theme-colors-05d50e3a.css",
colors: [
"#5d4bff",
// ...
],
};
这样就能获得到某个颜色对应的元素client.changer.changeColor(options, Promise);
// 首先判断 theme-colors.css 是否已经被插入到了文档,如果未插入则执行拉取然后再插入
setCssTo(elStyle, elStyle.innerText);
// 执行 Style 内置替换
function setCssTo(elStyle, cssText) {
cssText = _this.replaceCssText(cssText, oldColors, newColors);
elStyle.color = newColors.join("|");
elStyle.innerText = cssText;
theme_COLOR_config.colors = newColors;
}
// 直接全局替换样式方式进行切换
function replaceCssText(cssText, oldColors, newColors) {
oldColors.forEach(function (color, t) {
cssText = cssText.replace(
new RegExp(color.replace(/,/g, ",\\s*"), "ig"),
newColors[t]
); // 255, 255,3
});
return cssText;
}
alternate
<link href="reset.css" rel="stylesheet" type="text/css">
<link href="default.css" rel="stylesheet" type="text/css" title="默认">
<link href="red.css" rel="alternate stylesheet" type="text/css" title="红色">
<link href="green.css" rel="alternate stylesheet" type="text/css" title="绿色">
上面<link>
元素,共出现了
-
没有
title 属性,rel 属性值仅仅是stylesheet 的<link>
无论如何都会加载并渲染,如reset.css ; -
有
title 属性,rel 属性值仅仅是stylesheet 的作为默认样式CSS 文件加载并渲染,如default.css ; -
有
title 属性,rel 属性值同时包含alternate stylesheet 的作为备选样式CSS 文件加载,默认不渲染,如red.css 和green.css ;
这里有个非常有趣的特性,那就是
使用
// 渲染 red.css 这个皮肤
document.querySelector('link[href="red.css"]').disabled = false;
全局变量
Links
- https://alligator.io/css/theming-custom-properties/
- https://link.medium.com/QSCFGp1MzZ Theming in React with Styled Components