Vue前端换肤

2019-06-04  本文已影响0人  取个帅气的名字真好
换肤效果

本文采取 CSS自定义变量 实现

:root {
  --bg: red;
}

#test{
  background:var(--bg);
}
:root{} var()

注意:

  • 背景图片不支持这种写法 --bg:url('@/assets/bg1.jpg'); 需要换背景图片可在js中用 字符串模板 + require 设置。
    如:document.body.style.setProperty('--bg',`url(${require('@/assets/bg1.jpg')})`);

读取小坑。document.body.style.getPropertyValue('--bg'); 读取出来为空。
可换成如下代码:
const rootStyles = getComputedStyle(document.documentElement);
const varValue = rootStyles.getPropertyValue('--bg').trim(); //读取--bg值

完!!!


上代码吧!!

// test.vue

<template>
  <div id="test">
    <button @click="skin(1)">皮肤1</button>
    <button @click="skin(2)">皮肤2</button>
    <button @click="skin(3)">皮肤3</button>
    <p>使用 document.body.style.setProperty('--bg', 'red'); 来设置变量</p>
    <p>使用 document.body.style.getPropertyValue('--bg'); 来获取变量</p>
    <p>使用 document.body.style.removeProperty('--bg'); 来删除变量</p>
    <svg-icon icon-class="users" class-name="users"></svg-icon>
  </div>
</template>

<script>
  export default {
    data() {
      return {
      }
    },
    methods: {
      skin(e) {
        if (e === 1) {
          document.body.style.setProperty('--bg', '#7F583F');
          document.body.style.setProperty('--color', '#123');
          document.body.style.setProperty('--fontSize', '12px');
          document.body.style.setProperty('--fill', 'red');
        }
        if (e === 2) {
          document.body.style.setProperty('--bg', '#687');
          document.body.style.setProperty('--color', '#542');
          document.body.style.setProperty('--fontSize', '14px');
          document.body.style.setProperty('--fill', '#fff');
        }
        if (e === 3) {
          document.body.style.setProperty('--bg', `url(${require('@/assets/bg1.jpg')})`);
          document.body.style.setProperty('--color', 'red');
          document.body.style.setProperty('--fontSize', '16px');
          document.body.style.setProperty('--fill', '#000');
        }
      }
    },
  };
</script>

<style lang="scss" scoped>
  @import url('./index.scss');
</style>

// index.scss

:root{
  --bg:red;
  --color:#000;
  --fontSize:16px;
  --fill:red;
}
$color:var(--color);
#test {
  background:var(--bg);
  height:500px;
  width: 400px;
  font-size: var(--fontSize);
  color: $color;
  .users{
    fill: var(--fill);
    font-size: 100px;
  }
}

上一篇 下一篇

猜你喜欢

热点阅读