小程序中使用css var变量,使js可以动态设置css样式属性
发布于 4 年前 作者 qiangcai 4657 次浏览 来自 分享

使用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.com/s/aWfUGCmG7Efe

github

小程序演示

1 回复

为毛不直接在style=里用变量修改样式,还要再次通过css变量来修改?

回到顶部