前端主题颜色更换

271 阅读1分钟

CSS变量+类名切换

提前将样式文件载入,切换时将指定的根元素类名更换。在根作用域下定义好CSS变量,只需要在不同的主题下更改CSS变量对应的取值即可。

<template>
  <nav>
    <router-link to="/">Home</router-link> |
    <router-link to="/about">About</router-link>
  </nav>
  <div class="box"></div>
  <button @click="setTheme('default')">default</button>
  <button @click="setTheme('dark')">dark</button>
  <button @click="setTheme('pink')">pink</button>
  <router-view />
</template>
<script>
export default {
  methods: {
    setTheme(name) {
      document.documentElement.className = name;
    },
  },
};
</script>
<style lang="less">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}
:root {
  --theme-color: #333;
  --theme-background: #eee;
}
.dark {
  --theme-color: #eee;
  --theme-background: #333;
}
.pink {
  --theme-color: #fff;
  --theme-background: pink;
}

.box {
  transition: all 0.2s;
  width: 100px;
  height: 100px;
  border: 1px solid #000;
  color: var(--theme-color);
  background: var(--theme-background);
}
</style>
  • 不需要重新加载样式文件,在样式切换时不会有卡顿现象。
  • 在需要切换主题的地方利用var()绑定变量即可,不存在优先级问题。
  • 新增或修改主题方便灵活,仅需新增或修改CSS变量即可,在var()绑定样式变量的地方就会自动更换。

CSS变量+动态SetProperty

这种方案更适用于用户根据颜色面板自行设定各种颜色主题。 只需在全局中设置好预设的全局CSS变量样式,无需单独为每一个主题类名下重新设定CSS变量值,因为主题是由用户动态决定。

定义一个工具类方法,用于修改指定的CSS变量值,调用的是CSSStyleDeclaration.setProperty

:root {
  --theme-color: #333;
  --theme-background: #eee;
}
export const setCssVar = (prop: string, val: any, dom = document.documentElement) => {
  dom.style.setProperty(prop, val)
}