最近做了一个可动态切换主题颜色的管理系统,截取了部分代码记录一下这次颜色主题的解决方案。
- 创建themeVariable.scss文件,编写主题颜色自定义变量
//themeVariable.scss
$themes:(
"green":(
background:#ECECEC,
font-basis-color:#585858,
box-border:#D2D2D2,
),
"blue":(
background:#022059,
font-basis-color:#EFEFEF,
box-border:#185F86,
),
"black":(
background:#07080C,
font-basis-color:#D1D1D1,
box-border:#202330,
)
)
- 创建themeMixin.scss文件,编写自定义mixin
//themeMixin.scss
@import './themeVariable.scss'; //导入主题颜色变量
@mixin themeMixin {
@each $theme-name,
$map in $themes {
$theme-name: $theme-name !global; //全局变量供函数调用,如果无需全局调用,可不写!global
$themeMapList: $map !global; //全局变量供函数调用
//新定义一个类
.theme-#{$theme-name} {
@content; //插入位置
}
}
}
//从主题色map中取出对应颜色
@function themeAttrVal($themeAttrKey) {
@return map-get($themeMapList, $themeAttrKey);
}
- 在需要编写主题样式地方引入,在样式中使用@include 使用色值
@import './theme/themeMixin.scss';
@include themeMixin {
body {
background: themeAttrVal('background');
color: themeAttrVal('font-basis-color');
}
- 切换主题样式
// 改变主题色
changeTheme(theme) {
localStorage.setItem('theme', theme);
window.document.documentElement.setAttribute("class", theme);
}
还有一些特殊的情况。页面的的区块边框,在蓝色主题下需要做成发光边框,在绿色和黑色主题却不用,故需要做出一些特效的判断,这也是上面第二点的代码需要暴露$theme-name全局变量的原因。
@include themeMixin {
.box-bg{
border: 1px solid themeAttrVal('#box-border');
@if $theme-name=="blue" {
box-shadow: 0px 0px 10px #023A78 inset;
}
}