element-plus 一键动态换任何皮肤功能

参考效果

plus 官方代码给的思路
如果您想要通过 js 控制 css 变量,可以这样做:

// document.documentElement 是全局变量时
const el = document.documentElement
// const el = document.getElementById('xxx')

// 获取 css 变量
getComputedStyle(el).getPropertyValue(`--el-color-primary`)

// 设置 css 变量
el.style.setProperty('--el-color-primary', 'red')

但是你发现这样做之后,只是表面上换了个皮肤,像其它的操作,比如按钮hover,disabled 等的状态还是默认的颜色,就让你很不爽!

动态计算替换变量解决此问题

  • 安装插件 color
pnpm add color

实现思路就是把所有的 主色变量替换掉, 几行代码搞定

<template>
  <el-button type="primary" class="btn" size="default" @click="">
    Hello
  </el-button>
  <el-tag>Tag 1</el-tag>
  <el-color-picker
    v-model="color"
    show-alpha
    size="large"
    :predefine="predefineColors"
    @change="changeTheme"
  />
</template>
<script setup lang="ts">
import { ref } from 'vue'
import Color from 'color'
const color = ref('#f00')
const predefineColors = ref(['#ff4500', '#ff8c00', '#ffd700', '#90ee90'])
function changeTheme() {
  const el = document.documentElement
  el.style.setProperty('--el-color-primary', color.value)
  el.style.setProperty('--el-color-primary-dark-2', color.value)
  for (let i = 1; i < 10; i++) {
    el.style.setProperty(
      `--el-color-primary-light-${i}`,
      Color(color.value).alpha(`${(1 - i * 0.1).toFixed(1)}`)
    )
  }
}
changeTheme()
</script>
<style scoped></style>


  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值