小程序 动态绑定class

微信小程序提供了比较便捷的语法,使我们能够快速地动态绑定class
用法:
在一个标签的class里添加{{}}模板语法,模板里面是一个三元判别式,其中表达式一般引用data中的属性,表达式返回true或者false,A,B是class名,按照三元判别式的逻辑引用A或B 。
PS:
一个简单的例子:
index.wxml
类给按钮添加了蓝色边框,根据data中的属性isRed,选择按钮的背景色
微信小程序动态绑定样式测试
index.js
isRed属性设置成true
【小程序 动态绑定class】

小程序 动态绑定class

文章插图
//index.js//获取应用实例const app = getApp()Page({data: {motto: 'Hello World',userInfo: {},hasUserInfo: false,canIUse: wx.canIUse('button.open-type.getUserInfo'),isRed: true},})
index.wxss
/**index.wxss**/.border {border: 10rpx solid blue;margin-top: 50rpx;}.red {background-color: red;}.green {background-color: green;}
最终效果