前端切换主题颜色

文章介绍了如何使用CSS变量和自定义`theme-colors`属性实现网页的昼夜模式切换,通过``组件控制主题,并在不同主题下动态改变元素样式。
摘要由CSDN通过智能技术生成

自定义属性(–*):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;
}

 上述样式分析:具有 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变量了

  • 10
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值