/*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;
}
上述样式分析:具有 theme-colors 属性且属性值为 'dark'
的 <html>
元素
默认情况用
:root
定义的样式,黑夜模式用dark
,白天用white
设置标签样式
.card {
background: var(--theme-background);
}
切换主题操作
<!-- 换肤 -->
<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变量了