小程序中使用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变量试试呀

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

小程序演示

到此这篇关于小程序中使用css var变量的文章就介绍到这了,更多相关小程序使用css var变量内容请搜索呐喊教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持呐喊教程!

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。