【Element Plus】更换主题

989 阅读2分钟

暗黑模式

1、在 html 上添加一个名为 dark 的类

const htmlElement = document.documentElement
htmlElement.classList.add('dark')

2、导入 css 变量

import 'element-plus/theme-chalk/dark/css-vars.css'

思考

通过上述两步,我们的 Element Plus 就实现了暗黑模式

2024.12.24_曾超&b0f887e00f81fb0a6edbe0a6f23c663e.png

2024.12.24_曾超&fac9a657e185819baa602ec3241af500.png

原理:用暗黑模式的 css 变量覆盖亮色模式的 css 变量,使得组件在获取颜色时采用暗黑模式的 css 变量

拓展

知道了如何实现暗黑模式,那自定义主题就是用自定义的 css 变量去覆盖 Element Plus 提供的 css 变量

// 通过本段代码即可将 Element Plus 蓝变为自定义红
const htmlElement = document.documentElement
document.body.style.setProperty('--el-color-primary', '#f00')

主题色 & 色阶

美术提供了主题色之后,我们可以自行计算出 light-3、light-5 等不同色阶的值,原理就是通过将主题色放入 #ffffff(白色) 到 #000000(黑色) 间进行插值,后面的数值越大,主题色越暗,黑色白色反过来就是变亮

const colorMix = (color1, color2, weight) => {
  weight = Math.max(Math.min(Number(weight), 1), 0)
  const r1 = parseInt(color1.substring(1, 3), 16)
  const g1 = parseInt(color1.substring(3, 5), 16)
  const b1 = parseInt(color1.substring(5, 7), 16)
  const r2 = parseInt(color2.substring(1, 3), 16)
  const g2 = parseInt(color2.substring(3, 5), 16)
  const b2 = parseInt(color2.substring(5, 7), 16)
  const r = Math.round(r1 * (1 - weight) + r2 * weight)
  const g = Math.round(g1 * (1 - weight) + g2 * weight)
  const b = Math.round(b1 * (1 - weight) + b2 * weight)
  const rr = `0${(r || 0).toString(16)}`.slice(-2)
  const gg = `0${(g || 0).toString(16)}`.slice(-2)
  const bb = `0${(b || 0).toString(16)}`.slice(-2)
  return `#${rr}${gg}${bb}`
}
function changeThemeColor(config = {
      mode: 'light',
      primary: '#409eff',
      success: '#67c23a',
      ...
}) {
    const mixColor = {
      light: ['#ffffff', '#000000'],
      dark: ['#ffffff', '#000000']
    }
    const documentElement = document.documentElement as HTMLElement

    documentElement.setAttribute('class', config.mode === 'dark' ? 'dark' : '')
    Object.keys(config).forEach((key) => {
      if (key === 'mode') return
      const prefix = `--el-color-${key}`
      const initialColor = config[key]
      documentElement.style.setProperty(prefix, initialColor)
      ;[3, 5, 7, 8, 9].forEach((idx) => {
        const color = colorMix(initialColor, mixColor[config.mode][0], idx / 10)
        documentElement.style.setProperty(`${prefix}-light-${idx}`, color)
      })
      const color = colorMix(initialColor, mixColor[config.mode][1], 0.2)
      documentElement.style.setProperty(`${prefix}-dark-2`, color)
    })
  }
其他颜色

上述代码用于修改像 --el-color-primary、--el-color-success 这样的主题色、场景色

而除此之外的颜色变量 ex.--el-text-color-primary、--el-border-color 仍需通过本文拓展部分中的方法进行修改