# 前端模块化如何实现换肤

以前在做搜索的时候,接触过首页的换肤。但是那是还没有模块化开发,有的只是jquery。 所以那是的处理方法就是通过JQuery去修改标签的class名字,而每个class就对应一种皮肤,从而实现换肤功能。一切都是按照常规思路去解决。

可是,现在前端都是模块化开发。模块化开发后,组件都是有样式隔离的,所以全局的class还能换肤吗?

# 1.elementui实现步骤

  • 先把默认主题文件中涉及到颜色的 CSS 值替换成关键词:https://github.com/ElementUI/theme-preview/blob/master/src/app.vue#L250-L274
  • 根据用户选择的主题色生成一系列对应的颜色值:https://github.com/ElementUI/theme-preview/blob/master/src/utils/formula.json
  • 把关键词再换回刚刚生成的相应的颜色值:https://github.com/ElementUI/theme-preview/blob/master/src/utils/color.js
  • 直接在页面上加 style 标签,把生成的样式填进去:https://github.com/ElementUI/theme-preview/blob/master/src/app.vue#L198-L211

https://github.com/ElemeFE/element/issues/3054 https://elementui.github.io/theme-preview/#/zh-CN

# 2.less的 modifyVars方法

  • webpack less-loader 的modifyVars属性,可以实现更改less中的变量;

原理:

modifyVars方法是基于 less 在浏览器中的编译来实现。 所以在引入less文件的时候需要通过link方式引入,然后基于less.js中的方法来进行修改变量。

less.modifyVars({
  '@themeColor': 'pink'
});
1
2
3

link方式引入主题色文件

<link rel="stylesheet/less" type="text/css" href="./src/less/public.less" />
1

更改主题色事件

// color 传入颜色值
handleColorChange (color) {
    less.modifyVars({  // 调用 `less.modifyVars` 方法来改变变量值'
         @themeColor':color
         })
    .then(() => {
         console.log('修改成功');
    });
};
1
2
3
4
5
6
7
8
9

# 3.var变量方法

用法举例:

body{
   --themeColor:#000;
}
1
2
3

使用:

.main{
   color: var(--themeColor);
}
1
2
3

要修改主题色的话:

document.body.style.setProperty('--themeColor', '#ff0000');
1
最后更新时间: 11/7/2020, 4:54:46 PM