小程序中使用css var变量,使js可以动态设置css样式属性

使用sass,stylus可以很方便的使用变量来做样式设计,其实css也同样可以定义变量,在小程序中由于原生不支持动态css语法,so,可以使用css变量来使用开发工作变简单。

基本用法

基础用法

<!--web开发中顶层变量的key名是:root,小程序使用page-->
page { 
  --main-bg-color: brown;
}

.one {
  color: white;
  background-color: var(--main-bg-color);
  margin: 10px;
}

.two {
  color: white;
  background-color: black;
  margin: 10px;
}
.three {
  color: white;
  background-color: var(--main-bg-color);
}

提升用法

<div class="one">
  <div class="two">
    <div class="three">
    </div>
    <div class="four">
    </div>
  <div>
</div>
.two { --test: 10px; }
.three { --test: 2em; }

在这个例子中,var(--test)的结果是:

class=”two” 对应的节点: 10px
class=”three” 对应的节点: element: 2em
class=”four” 对应的节点: 10px (继承自父级.two)
class=”one” 对应的节点: 无效值, 即此属性值为未被自定义css变量覆盖的默认值

上述是一些基本概念,大致说明css变量的使用方法,注意在web开发中,我们使用:root来设置顶层变量,更多详细说明参考MDN的 文档

妙用css变量

开发中经常遇到的问题是,css的数据是写死的,不能够和js变量直通,即有些数据使用动态变化的,但css用不了。对了,可以使用css变量试试呀

wxml

js

// 在js中设置css变量
let myStyle = `
--bg-color:red; 
--border-radius:50%;
--wid:200px;
--hgt:200px;
`

let chageStyle = `
--bg-color:red; 
--border-radius:50%;
--wid:300px;
--hgt:300px;
`
Page({
  data: {
    viewData: {
      style: myStyle
    }
  },
  onLoad(){
    setTimeout(() => {
      this.setData({'viewData.style': chageStyle})
    }, 2000);
  }
})

wxml

<!--将css变量(js中设置的那些)赋值给style-->
<view class="container">
  <view class="my-view" style="{{viewData.style}}">
    <image src="/images/abc.png" mode="widthFix"/>
  </view>
</view>

wxss

/* 使用var */
.my-view{
  width: var(--wid);
  height: var(--hgt);
  border-radius: var(--border-radius);
  padding: 10px;
  box-sizing: border-box;
  background-color: var(--bg-color);
  transition: all 0.3s ease-in;
}

.my-view image{
  width: 100%;
  height: 100%;
  border-radius: var(--border-radius);
}

通过css变量就可以动态设置css的属性值

代码片段

https://developers.weixin.qq….

github
小程序演示

作者:天天修改

  • 12
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值