赞
踩
已经做了一半的系统,突然提出要添加一个切换亮色和暗色主题的需求,第一反应想到的就是使用变量,总体思路就是:在html标签中添加自定义属性用来识别时亮色还是暗色,scss再通过这个属性来获取对应的颜色变量
1、主题变量文件(scss文件),主要用来保存要使用的变量颜色,分别对应亮色和暗色
$themes: (Bright: (
moduleBackColor: #FFFFFF, // 模块底色
backColor: #eff4f8, // 页面底色
mapColor: #FFFFFF, // 地图背景颜色
iconColor: #C5CEE8, // 图标颜色
), Dark: (
moduleBackColor: #1B1A1F, // 模块底色
backColor: #000000, // 页面底色
mapColor: #1B1A1F, // 地图背景颜色
iconColor: #494D60, // 图标颜色
));
2、定义一个获取变量的函数文件 handle.scss,用于从主题色中取出具体的颜色
@import "./themes.scss"; // 切换主题,获取不同的主题色 @mixin themeify { @each $theme-name, $theme-map in $themes { //!global 把局部变量强升为全局变量 $theme-map: $theme-map !global; //判断html的data-theme的属性值 #{}是sass的插值表达式 //& sass嵌套里的父容器标识 @content是混合器插槽,像vue的slot [data-theme="#{$theme-name}"] & { @content; } } } //从主题色map中取出对应颜色 @function themed($key) { @return map-get($theme-map, $key); } //获取模块底色 @mixin module_background_color($color) { @include themeify { background-color: themed($color)!important; } }
// 设置自定义属性,挂载默认的亮色主题
window.document.documentElement.setAttribute('data-theme', 'Bright')
如果需要切换主题就修改自定义属性
//修改为暗色主题
window.document.documentElement.setAttribute('data-theme', 'Dark')
// 修改为亮色主题
window.document.documentElement.setAttribute('data-theme', 'Bright')
在要使用的文件中引入这两个文件
@import '@/assets/styles/themes.scss';
@import '@/assets/styles/handle.scss';
然后就可以在文件中使用了
.main-table {
@include module_background_color('moduleBackColor');
height: 98%;
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
}
亮色
点击切换主题后变为暗色
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。