惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
aimingoo的专栏
aimingoo的专栏
腾讯CDC
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
F
Fortinet All Blogs
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园_首页
B
Blog RSS Feed
D
Docker
M
MIT News - Artificial intelligence
爱范儿
爱范儿
I
InfoQ

博客园 - ฅ˙-˙ฅ

js中常见内存泄漏和场景 用display实现效果:上面根据内容自适应高度;下面撑满所有,并且超出时候显示滚动条 react更改多层对象变量的方法 react umi model使用注意事项 拖动改变顺序 博文阅读密码验证 - 博客园 antd input控制只能输入数字并进行格式化显示(antd 3版本) react函数式组件:父组件调用子组件方法 react form表单中自定义组件的数据双向绑定实现 vue3+vant h5: Rem 移动端布局适配之postcss-pxtorem和lib-flexible 项目记录文档 前端mock方案:使用json-server mac安装使用nginx 博文阅读密码验证 - 博客园 umi修改antd主题颜色(通过less文件修改) 部署一个vue项目到阿里云服务器 vue项目通过点击按钮实现复制图片(非图片url和base64),可发送到聊天框 vue重新刷新当前路由(非浏览器强刷,不会出现闪屏) 使用Vue.extend实现iview Upload在单文件上传时,拖拽多个文件给出错误提示 uni-app怎么使用路由守卫,并且路由配置和pages.json中只写一套 uni-app小程序iPhone X适配底部栏黑横线
使用css自定义变量实现实现主题切换功能
ฅ˙-˙ฅ · 2020-08-26 · via 博客园 - ฅ˙-˙ฅ

前言

之前,写过一篇基于less自定义函数实现主题切换功能
此种方法缺陷:

  • 从原本的项目中抽离样式比较繁琐;
  • 自定义函数传参方式,可读性比较差,容易造成传参混淆;
  • 因为主题自定义函数中定义的类是共用的,如果不同组件中类重名了,会影响到每个组件;需要在自定义函数中定义一个唯一命名的类,然后在需要使用该主题样式的地方进行引入;这无形中又增加了切换主题的复杂度;

所以上篇文章最后提到的关于切换css变量的方式,个人觉得,还是简介明了。所以接下来就介绍一下 使用css自定义变量实现实现主题切换功能

实现步骤

1. 切换主题,为body添加不同类名

<template>
  <div>
    <Select v-model="theme" @on-change="changeTheme">
      <Option v-for="item in themes" :value="item.value" :key="item.value">{{ item.name }}</Option>
    </Select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      themes: [
        { name: '白色主题', value: 'theme-light' },
        { name: '黑色主题', value: 'theme-dark' },
      ],
      theme: '',
    };
  },
  methods: {
    changeTheme(theme) {
      window.localStorage.setItem('theme', theme);
      // 设置body类
      const body = document.querySelector('body');
      this.themes.forEach((t) => {
        body.classList.remove(t.value);
      });
      body.classList.add(theme);
    },
  },
  created() {
    // 初始化获取主题
    this.theme = window.localStorage.getItem('theme') || this.themes[0].value;
    // 设置body类
    const body = document.querySelector('body');
    body.classList.add(this.theme);
  },
};
</script>

2. 针对不同类名,为css自定义变量赋值

比如theme-light.less中

.theme-light {
      --color: #fff;
}

theme-dark.less中

.theme-dark {
      --color: #000;
}

3. 项目中引入保存主题变量的less文件

@import "~@/styles/theme/theme-light.less";
@import "~@/styles/theme/theme-dark.less";

4. 使用css自定义变量

.header{
     color: var(--color); 
}

综上,整体思路:切换主题时,为body赋值不同类,每个类下为css变量赋不同颜色值;