当用户点击按钮时,视图的高度会在0和原始高度之间切换,从而实现视图的展开和折叠。
初始化视图的高度:在页面准备就绪(onReady)时,使用wx.createSelectorQuery获取.box1视图的高度,并将其存储在boxHeight和height中。
切换视图的展开和折叠:当用户点击按钮(通过bind:tap="toggleDiv"绑定的事件)时,toggleDiv函数会被触发。这个函数会切换isCollapse的值,并根据isCollapse的值来设置boxHeight。如果isCollapse为真,boxHeight会被设置为0,从而折叠视图。如果isCollapse为假,boxHeight会被设置为height,从而展开视图。
<button bind:tap="toggleDiv">154654665465</button>
<view class="box1" id="box1" style="height:{{boxHeight}}px;">
<view class="box1-item"></view>
<image src="" mode=""/>
<view class="box1-item"></view>
<view class="box1-item"></view>
<view class="box1-item"></view>
<view class="box1-item"></view>
</view>
<view>111</view>
<view>111</view>
<view>111</view>
<view>111</view>
.box1 {
/* width: 200rpx; */
background-color: #bfa;
transition: height 1s;
overflow: hidden;
}
.box1 .box1-item {
height: 20rpx;
border: 1rpx solid red;
}
data: {
isCollapse: false,
height:0
},
onReady() {
var that = this;
var pack = wx.createSelectorQuery();
pack.select('.box1').boundingClientRect(function (rect) {
that.setData({
boxHeight: rect.height,
height: rect.height
});
}).exec();
},
toggleDiv(){
this.setData({ isCollapse: !this.data.isCollapse })
var that = this;
if(that.data.isCollapse) {
that.setData({
boxHeight: 0
});
}else{
let unfold = wx.createSelectorQuery();
unfold.select('.box1').boundingClientRect(function (rect) {
that.setData({
boxHeight: that.data.height
});
}).exec();
}
},