【css学习】使用css3中的var实现主题切换

一,首先搭建基础的页面结构
<template>
  <div>
    <button>切换主题1</button>
    <button>切换主题2</button>

    <h1>这是一段测试文字</h1>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 默认背景颜色
      themeBgColor: '#fff',
      // 默认文字颜色
      themeColor: '#000'
    }
  }
}
</script>

<style>

</style>

这里是一段普通的基础代码,里面有两个用于切换主题的按钮,和一段测试文字

二,使用css3中的var创建样式变量

这里使用了–bgColor和–textColor样式变量,并且将vue中声明的变量赋值,使默认样式生效

注意点1:样式变量名必须要--开头
注意点2:在style标签中使用样式变量需要用var函数

<template>
  <div
    class="container"
    :style="{
      '--bgColor': themeBgColor,
      '--textColor': themeColor,
    }"
  >
    <button>切换主题1</button>
    <button>切换主题2</button>

    <h1 class="text">这是一段测试文字</h1>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 默认背景颜色
      themeBgColor: '#fff',
      // 默认文字颜色
      themeColor: '#000'
    }
  }
}
</script>

<style>
.container {
  background: var(--bgColor);
}

.text {
  color: var(--textColor);
}
</style>

基本的样式架构已经搭建好了,接下来就是动态改变vue中的变量,来达到动态切换主题的效果…

三,动态切换主题

这里给两个主题切换按钮绑定事件,传入不同的参数,使样式变量和vue中的变量关联,达到切换主题的效果

<template>
  <div
    class="container"
    :style="{
      '--bgColor': themeBgColor,
      '--textColor': themeColor,
    }"
  >
    <!-- 绑定切换主题事件 -->
    <button @click="changeTheme('#000', '#fff')">切换主题1</button>
    <button @click="changeTheme('red', 'yellow')">切换主题2</button>

    <h1 class="text">这是一段测试文字</h1>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 默认背景颜色
      themeBgColor: '#fff',
      // 默认文字颜色
      themeColor: '#000'
    }
  },
  methods: {
    changeTheme (bgColor, textColor) {
      this.themeBgColor = bgColor
      this.themeColor = textColor
    }
  }
}
</script>

<style>
.container {
  background: var(--bgColor);
}

.text {
  color: var(--textColor);
}
</style>
四,如果你没有使用vue,而是想用原生js来实现动态主题切换,那么你可以采用下面的写法

我们可以使用js提供的setProperty来主动修改dom节点上的style属性,也能达到动态修改主题的效果

<template>
  <div
    class="container"
    :style="{
      '--bgColor': '#fff',
      '--textColor': '#000',
    }"
  >
    <!-- 绑定切换主题事件 -->
    <button @click="changeTheme">切换主题</button>

    <h1 class="text">这是一段测试文字</h1>
  </div>
</template>

<script>
export default {
  data () {
    return {
    }
  },
  methods: {
    changeTheme () {
      document.querySelector('.container').style.setProperty('--bgColor', 'yellow')
      document.querySelector('.container').style.setProperty('--textColor', 'red')
    }
  }
}
</script>

<style>
.container {
  background: var(--bgColor);
}

.text {
  color: var(--textColor);
}
</style>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值