本文的换肤方案灵感来自于 element-ui
需求:网站换肤,主题切换。网站的主题色可以在几种常用颜色之间进行切换,还有相关图片、图标也要跟随主题进行切换。
不多说,先看下最终的实现效果:

文章由两部分组成:css切换,图片图标切换
css切换
1.在 static 目录下新建一个 styles 文件夹,在 styles 下新建一个 theme.scss 文件(项目使用了sass,会自动编译成css文件,如果没有使用这些预处理工具可以直接新建 theme.css),将需要替换的 CSS 声明在此文件中。
.theme-test-btn {
background-color: #409eff;
border-color: #409eff;
}.theme-test-btn:hover,
.theme-test-btn:focus {
background-color: #66b1ff;
border-color: #66b1ff;
}
2.在 src/assets/js/const/ 目录下新建 theme-colors.js,用于声明所有可选的主题,每种颜色都对应一个关键词,方便区分
const colors = [
{
themeId: 0,
primaryBtn: '#409eff', // 主要按钮的背景色
priBtnHover: '#66b1ff', // 主要按钮的悬浮、聚焦背景色
},
{
themeId: 1,
primaryBtn: '#67c23a',
priBtnHover: '#85ce61',
},
{
themeId: 2,
primaryBtn: '#e6a23c',
priBtnHover: '#ebb563',
},
];export default colors;
3.通过 ajax 获取 theme.css ,将颜色值替换为关键词。
data() {
return {
active: 0,
themeStyleStr: '', // 存放 替换成关键词的 theme.css 内容
colors: themeColors, // 所有可选的主题颜色数组。即:theme-colors.js 文件export的数组
};
},
mounted() {
// 通过 ajax 获取 theme.css 的内容,并将颜色值替换为关键词
this.$http.getThemeFile().then(res => {
this.themeStyleStr = this.getStyleTemplate(res);
});
},
methods: {
// 获取样式模板:将颜色值替换为关键词。
getStyleTemplate(data) {
let color = this.colors[0];
delete color.themeId;
let colorMap = {};
Object.keys(color).forEach(key => {
colorMap[color[key]] = key;
});
Object.keys(colorMap).forEach(key => {
data = data.replace(new RegExp(key, 'ig'), colorMap[key]);
});
return data;
},
}this.$http.getThemeFile 方法
// 使用原生ajax获取换肤的样式文件
getThemeFile() {
return new Promise(resolve => {
const url = location.origin + '/static/styles/theme.css';
const xhr = new XMLHttpRequest();










