记录 学到css使用js变量,可以用来实现主题切换等功能

使用css 中的 var() 函数实现 css调用js变量

  1. 在最外层的标签上加上自定义css属性
//一定要写在最外层||父级的div上
<div style='--mianColor: #f00'>
</div>
  1. 定义一个sass变量 全局使用,需要的地方使用这个scss变量
$mainColor: var(--mainColor);
.content {
	color: $mainColor;
}
  1. --mainColor弄成变量 修改initTheme即可全局更改使用$mainColor的元素
<template>
	<div :style='initTheme'>
		
	</div>
<template>
<script>
export default {
	data() {
		return {
			initTheme: {
				'--mainColor': '#f00'
			}
		}
	}
}
</script>
  1. 完整代码codepen可直接运行
<!-- Use preprocessors via the lang attribute! e.g. <template lang="pug"> -->
<template>
  <div id="app" :style='mainConfig'>
    <button @click='changeMain'>切换主题</button><br /><br /><br />
    <a>asdfasdfasd</a>
    <div class='content'>背景颜色的地方</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      color: '#f00',
      message: 'Welcome to Vue!',
      mainConfig: {
        "--mainColor" : '#f00',
        "--mainBackground" : '#fa3',
      }
    };
  },
  methods: {
    changeMain() {
      this.mainConfig['--mainColor'] = this.getRandomColor()
      this.mainConfig["--mainBackground"] = this.getRandomColor()
    },
    getRandomColor() {
      var r = Math.floor(Math.random() * 256); // 生成0-255之间的随机整数作为红色通道值
      var g = Math.floor(Math.random() * 256); // 生成0-255之间的随机整数作为绿色通道值
      var b = Math.floor(Math.random() * 256); // 生成0-255之间的随机整数作为蓝色通道值

      var color = "rgb(" + r + "," + g + "," + b + ")";
      return color;
    }
  }
};
</script>

<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
  
$mainColor: var(--mainColor);
$mainBackground: var(--mainBackground);
  
a {
  color: $mainColor;
}
  .content {
    color: $mainColor;
    background: $mainBackground; 
  }
</style>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值