一些网站通常会提供白天、夜间模式,以及自定义主题等等,这种主题切换也就是本文说的前端换肤。
这次案例用的是白天和夜间模式的切换,在做换肤之前,得先晓得一件事件:css的变量定义,对变量定义不相熟的同学请看MDN
文档:自定义属性(--*):CSS 变量
主题切换也就是款式的切换,白天和黑夜的模式切换须要筹备两套款式,咱们通过css
的变量定义,全局拜访这些公共变量就能够实现主题切换。
此处我曾经筹备好了款式:
/*style.css*//* 根本款式 */:root { --theme-background: #ecf5ff; /*背景色*/ --theme-menuBackground : #fff; /*菜单色彩*/ --theme-menuIcon : #303133; /*菜单icon*/}/* 黑夜模式 */html[theme-colors='dark'] { --theme-background: #1b1b1b; /*背景色*/ --theme-menuBackground : #343434; /*菜单色彩*/ --theme-menuIcon : #cdcdcd; /*菜单icon*/ --theme-activeColor : #97a1fe;}/* 白天 */html[theme-colors='white'] { --theme-background: #ecf5ff; /*背景色*/ --theme-menuBackground : #fff; /*菜单色彩*/ --theme-menuIcon : #303133; /*菜单icon*/ --theme-activeColor : #97a1fe;}
默认状况用:root
定义的款式,黑夜模式用dark
,白天用white
公共样变量定义后,咱们就能够到页面应用了,例如设置卡片的背景色:
.card { background: var(--theme-background); }
此时拜访的是:root
中的默认变量,咱们须要做到依据按钮切换,拜访不同主题下的变量
<!-- 换肤 --><el-switch v-model="theme" inline-prompt style="--el-switch-on-color: #13ce66; --el-switch-off-color: #97a0ff" :active-icon="Sunny" :inactive-icon="Moon" @change="themeChange"/>
// 主题切换const theme = ref<boolean>(true);const themeChange = (val : boolean) => { // true白天 false夜晚 if(val){ document.querySelectorAll('html')[0].setAttribute('theme-colors','white') } else { document.querySelectorAll('html')[0].setAttribute('theme-colors','dark') }}
setAttribute()
设置指定元素上的某个属性值。如果属性曾经存在,则更新该值;否则,应用指定的名称和值增加一个新的属性。如果要切换夜间模式,咱们能够给html
设置一个属性为theme-colors = dark
,此时咱们就能够拜访html[theme-colors='dark']
下的css
变量了
,白天模式切换theme-colors = white
即可。
在做我的项目之前咱们能够思考到这一点,否则前期页面都写好了再改会比拟麻烦。如果用了前端框架的话,咱们须要笼罩框架自带的款式,咱们能够将笼罩的款式写成公共文件,全局引入或者在对应页面引入即可。
如果感觉这篇文章对你有帮忙,欢送点赞、珍藏、转发✨哦~