1.使用Window全局变量,把当前皮肤名称变量写入全局,
const colorList = ['default','red','green']; //全局变量
Window.themeColor=colorList[0]; //写入Window对象
2.使用less生成对应皮肤的样式,使用less中的变量函数,通过不同的颜色参数生成对应颜色的皮肤;
在less中设置主题色变量
@theme-color : #226CDC; //默认主题色
@red-theme-color:#fe2419;
@green-theme-color:#226CDC;
用header举例主题色样式写法,html略
.header-style(@theme-color:@theme-color){ // less函数
.header {
height: 4.68vw;
background: @theme-color;
background-size: 100%;
position: fixed;
width: 100%;
top: 0;
z-index: 98;
.back-btn {
height: 100%;
width: 4.68vw;
position: absolute;
left: 0;
top: 0;
a {
display: flex;
height: 100%;
width: 100%;
align-items: center;
.icon{
width: 100%;
height: 1.71875vw;
fill: #fff;
}
}
}
.title {
text-align: center;
color: #fff;
font-size: 1.5625vw;
height: 100%;
span {
display: block;
font-size: 1.5625vw;
font-weight: bold;
height: 100%;
line-height: 4.68vw
}
}
.control-bar {
position: absolute;
right: 0;
top: 0;
display: flex;
z-index: 98
}
}
}
//调用函数生成相应的样式
.header-style(); // 默认主题色
.red{ // 这里需要单独添加一个class 用来换肤
.header-style(@red-theme-color); // 红色
}
.green{
.header-style(@green-theme-color); //绿色
}
3.通过更改body的class名称,实现换肤(核心)
let themeColor = localStorage.getItem('themeColor'); // 判断是否已存在使用的皮肤
if (themeColor) {
window.cssStyle=colorList[Number(themeColor)];
}else {
localStorage.setItem('themeColor','0'); // 不存在则储存一个默认的主题色
}
document.body.classList.add(window.cssStyle); //body 添加less中主题色的class
4.换肤按钮事件,更改皮肤
changeColor(colortype,e){
e.stopPropagation();
localStorage.setItem('themeColor',colortype); //保存使用主题色
document.body.classList.remove(window.cssStyle); //去除已有主题色
window.cssStyle=colorList[Number(colortype)]; //获取新的主题色
document.body.classList.add(window.cssStyle); //body添加主题色的class
}
调用changeColor函数更改主题色,changeColor(''1''),changeColor(''0'')
注意:在vue中需要在页面渲染完以后在执行body添加class的操作。
整体换肤的思路就是通过less生成对应主题色样式,给每一套主题样式添加一个class,然后通过修改body的class即可实现主题色切换,自己学习记录,希望能给诸君带来一点启发。
THE END