环境
系统: win10 64 node版本 v16.13.2 vue: ^3.2.33 element-plus: ^2.2.0
开始
|| 本文换肤的实现思路是手动定制多套主题,然后进行动态切换与 相似。 主要实现分为两块 获取主题文件。 根据主题类型使用函数进行动态切换加载css变量。
获取主题文件
文件内容太长了从示例仓库复制 或者直接拷贝仓库themes.js文件放到项目中。 当然这么多css 变量不是每个都需要改的,本文作为示例文章所以存入了全部的变量(能获取到的)。个人依实际情况进行删减保留!!!
根据主题类型使用函数进行动态切换加载css变量
data() {
return {
currentSkinName: darkTheme,
themeColorObj: {
defaultTheme: {
title: 浅色主题
},
darkTheme: {
title: 深色主题
}
},
themeObj: {
}
};
},
mounted() {
this.switchTheme()
},
methods: {
// 根据不同的主题类型 获取不同主题数据
switchTheme(type) {
// themes 对象包含 defaultTheme、darkTheme 两个属性即默认主题与深色主题
this.currentSkinName = type || darkTheme
this.themeObj = themes[this.currentSkinName]
this.getsTheColorScale()
// 设置css 变量
Object.keys(this.themeObj).map(item => {
document.documentElement.style.setProperty(item, this.themeObj[item])
})
},
// // 获取色阶
getsTheColorScale() {
const colorList = [primary, success, warning, danger, error, info]
const prefix = --el-color-
colorList.map(colorItem => {
for (let i = 1; i < 10; i += 1) {
if (i === 2) {
// todo 深色变量生成未完成 以基本色设置
this.themeObj[`${
prefix}${
colorItem}-dark-${
2}`] = colorMix(this.themeObj[`${
prefix}black`], this.themeObj[`${
prefix}${
colorItem}`], 1)
} else {
this.themeObj[`${
prefix}${
colorItem}-light-${
10 - i}`] = colorMix(this.themeObj[`${
prefix}white`], this.themeObj[`${
prefix}${
colorItem}`], i * 0.1)
}
}
})
}
}
colorMix函数 仓库示例是在 src -> utils -> tool.js 导出。
const colorMix = (color1, color2, weight) => {
weight = Math.max(Math.min(Number(weight), 1), 0)
let r1 = parseInt(color1.substring(1, 3), 16)
let g1 = parseInt(color1.substring(3, 5), 16)
let b1 = parseInt(color1.substring(5, 7), 16)
let r2 = parseInt(color2.substring(1, 3), 16)
let g2 = parseInt(color2.substring(3, 5), 16)
let b2 = parseInt(color2.substring(5, 7), 16)
let r = Math.round(r1 * (1 - weight) + r2 * weight)
let g = Math.round(g1 * (1 - weight) + g2 * weight)
let b = Math.round(b1 * (1 - weight) + b2 * weight)
r = ("0" + (r || 0).toString(16)).slice(-2)
g = ("0" + (g || 0).toString(16)).slice(-2)
b = ("0" + (b || 0).toString(16)).slice(-2)
return "#" + r + g + b;
}
主题切换的一些疑问
切换主题的 css变量 是从哪里获取的?
打开 elementPlus-ui f12 审查元素。拿取所有 css变量。
switchTheme 函数中的获取基本色色阶是什么?
就是图片的里的变量,控制如navmenu导航 hover 的背景色等…
网站与主题颜色同步更改
项目内需要跟随主题改变的颜色,使用主题的css变量即可如:
参考文章
往期文章
最后