网站换肤的实现

2021-02-26  本文已影响0人  菜蚴菜

针对整个网站需要改变主题的情况

一、方案1:通过设置属性选择器来实现

1、新建不同主题的scss

default.scss
//:root 选择器匹配文档根元素,在 HTML 中,根元素始终是 html 元素。
:root{
  --color-title: #333;
}
green.scss
[theme='green']{
  --color-title: green;
}
red.scss
[theme='red']{
  --color-title: red;
}

在一个公共的scss中引入

theme.scss
@import './default.scss';
@import './green.scss';
@import './red.scss';

2、在main.js中全局引入

import '@/styles/theme.scss' 

3、在入口的vue文件中拿到拼接在url上的主题字段theme,把theme值作为body体的一个属性

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  name: "App",
  computed: {
    theme() {
      return this.$route.query.theme;
    },
  },
  mounted() {
    this.updateTheme();
  },
  watch: {
    theme() {
      this.updateTheme();
    },
  },
  methods: {
    updateTheme() {
      let { theme } = this;
      const root = document.body;
      if (theme) {
        root.setAttribute("theme", theme);
      } else {
        if (root.getAttribute("theme")) {
          root.removeAttribute("theme");
        }
      }
    },
  },
};
</script>
<style lang="scss">
#app {
   
}
</style>

访问页面/?theme=green,在页面元素中看到的实际运行结果如下:

<body theme="green">
</body>

此时,通过css的属性选择器匹配到theme主题下变量的值

[theme=green] {
   --color-title: green;
}

4、在具体的页面中,通过var来获取到对应的值

 color:var(--color-title);
二、方案2:通过往root下动态塞入变量的形式

1、在html文件的头部预设一个元素

  <style id="theme"></style>
const themeWhite={
 --color-title: #ffffff;
}
const themeDark={
 --color-title: black;
}
let themeCss=theme==='dark'?themeDark:themeWhite;
 const innerText = Object.keys(themeCss)
    .map((cssVar) => {
      // console.log(cssVar);
      return `${cssVar}:${themeCss[cssVar]}`;
    })
    .join(';');
  el.innerText = `:root {${innerText}}`;
上一篇 下一篇

猜你喜欢

热点阅读