vue3 + typescript 中,使用 ui 框架,修改主题色

前言

1、 这里展示的是 element plus 实现的 主题色却换功能。
2、当前功能适用与所有类似 element plus css 变量声明结构

内容

// 引入本地存储 localStorage 模块
import localStorageItem from "@/utils/localStorageItem";

// 主题色设置
export default class ThemeSet {
    
    
	// 定义内部变量
    private static mixWhite = "#ffffff";
    private static node = document.documentElement;
    private static color: string | undefined = void 0;
    private static hexadecimal = /^#?([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
    private static local: string | undefined = JSON.parse(localStorageItem.getItme("themeColor") as string);
    
    // 修改主题色
    public static themeColor(color?: string, themeClass: string = '--el-color-primary') {
    
    
        color ? this.color = color : this.local ? this.color = this.local : "";
        if (!this.color) return;
        // 校验颜色进制是否为 16 进制
        if (!this.hexadecimal.test(this.color)) {
    
    
            throw new Error(`
                ${
      
      this.color} 不是十六进制字符!!!
                This method is only applicable to the "hexadecimal"!!!
            `);
        };
        // 存储主题色
        localStorageItem.setItme("themeColor", this.color);
        // 设置主题色主色
        this.node.style.setProperty(themeClass, this.color);
        // 设置功能性 active (也就是鼠标按下的元素显示的颜色)
        this.node.style.setProperty(`${
      
      themeClass}-dark-2`, this.mix(this.color, this.mixWhite, .6));
        // 设置次级色调
        for (let i = 1; i < 10; i += 2) {
    
    
            this.node.style.setProperty(`${
      
      themeClass}-light-${
      
      i}`, this.mix(this.color, this.mixWhite, i * 0.1));
        };
    };

    // 次级色调设置
    private static mix(color1: string, color2: string, weight: number) {
    
    
        // 透明比
        weight = Math.max(Math.min(Number(weight), 1), 0);
        // rgb 计算
        const r1 = parseInt(color1.substring(1, 3), 16);
        const g1 = parseInt(color1.substring(3, 5), 16);
        const b1 = parseInt(color1.substring(5, 7), 16);
        // rgb 计算
        const r2 = parseInt(color2.substring(1, 3), 16);
        const g2 = parseInt(color2.substring(3, 5), 16);
        const b2 = parseInt(color2.substring(5, 7), 16);
        // rgb 组合
        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);
        // 结果运算 16 进制转化
        const _r = ('0' + (r || 0).toString(16)).slice(-2);
        const _g = ('0' + (g || 0).toString(16)).slice(-2);
        const _b = ('0' + (b || 0).toString(16)).slice(-2);

        return '#' + _r + _g + _b;
    };
};


猜你喜欢

转载自blog.csdn.net/weixin_44244230/article/details/128222558