需求:
设计三套主题色+部分图标更换;
实现方式汇总:
1.传统做法,生成多套css主题包,切换link引入路径切换href实现,参考网站:http://jui.org/;或者是将多套样式一起打包,不过每套样式需要添加不同的前缀名称用于区分,这样直接在body上利用js切换class名称即可:
toggleClass(element, className) {if (!element || !className) {return;
}
element.className=className;
}//点击按钮切换
this.toggleClass(document.body, ‘theme-1‘);
2.饿了么官方demo:直接在页面上插入 style 标签样式,利用样式优先级强行覆盖(不推荐),具体步骤:
3.利用html引用css生效原生属性进行切换(推荐):如果是elementUI推荐使用sass,antd推荐使用less(注意编译速度);
window.document.documentElement.setAttribute(‘data-theme‘, ‘theme1’)
elementUI实战:
1.准备工作:
安装:vue+elementUI+sass
配置:以上版本问题、自行在官网查阅,关于sass推荐一个网站https://www.sassmeister.com/
2.demo:
页面:
theme1
theme2
theme3
methods: {
changeTheme (theme) {
window.document.documentElement.setAttribute(‘data-theme‘, theme)
}
}
}
sass配置:
1.主题文件theme.scss
//主题色
$font-color-theme1 : #3f8e4d;//字体默认颜色
$font-color-theme2 : red;//$background-color-theme1: #3f8e4d;//默认主题颜色
$background-color-theme2: red;
$font-color-shallow0 : #000;
$font-color-shallow1 : #111;
$font-color-shallow2 : #222;
$font-color-shallow3 : #333;
$font-color-shallow4 : #444;
$font-color-shallow5 : #555;
$font-color-shallow6 : #666;
$font-color-shallow7 : #777;
$font-color-shallow8 : #888;
$font-color-shallow9 : #999;//字体定义规范
$font_little_s:10px;
$font_little:12px;
$font_medium_s:14px;
$font_medium:16px;
$font_large_s:18px;
$font_large:20px;
2.公共变量文件
@import "./theme";/*引入配置*/@mixin font_size($size){/*通过该函数设置字体大小,后期方便统一管理;*/@include font-dpr($size);
}
@mixin font_color($color){/*通过该函数设置字体颜色,后期方便统一管理;*/color:$color;
[data-theme="theme1"] &{
color:$font-color-theme1;
}
[data-theme="theme2"] &{
color:$font-color-theme2;
}
}
@mixin bg_color($color){/*通过该函数设置主题颜色,后期方便统一管理;*/background-color:$color;
[data-theme="theme1"] &{
background-color:$background-color-theme1;
}
[data-theme="theme2"] &{
background-color:$background-color-theme2;
}
}
3.修改elment组件样式变量:如alert
@import "./common/var";
@include b(alert) {
width:100%;
padding: $--alert-padding;
margin:0;
box-sizing: border-box;
border-radius: $--alert-border-radius;
position: relative;//background-color: $--color-white;
@include bg_color(background-color);
overflow: hidden;
opacity:1;
display: flex;
align-items: center;
transition: opacity .2s;
@include when(light) {//默认
.el-alert__closebtn {//color: $--color-text-placeholder;
@include font_color(color);
}
}
参考推荐: