需求背景
项目需要做一个swiper切换栏,但是每个swiper-item中有一个类似手风琴风格的收缩栏,展开后其内容不定,高度不定,无法预知,由于微信小程序的swiper组件并不是自适应高度的,所以就需要通过某些方法使其自适应
首先要动态设置swiper高度,就应该先将swiper组件的高度设置为动态值,并根据收缩栏收起时的最小高度初始化为一个默认值
<swiper bindchange="swiperChange" previous-margin="20px" next-margin="10px" style="height: {{ swiperHeight }}rpx"></swiper>
data: { 'swiperHeight' : '1240', 'isToggle' : false ,//收缩栏是否展开控制器 },
最重要的便是如何获取收缩栏展开后展开部分的高度,并动态设置swiper的高度,这里使用的是微信小程序的节点选择器
//创建节点选择器,动态获取面板高度设置动画高度 var query = wx.createSelectorQuery(); query.select('#收缩栏面板展开部分容器id').boundingClientRect() query.exec(function (res) { //res[0].height 为获取的收缩栏面板展开部分的高度 finalHeight = that.data.swiperHeight + res[0].height ; that.setData({ 'isToggle' : !that.data.isToggle , 'swiperHeight' : finalHeight }) })
同理当收缩栏收缩时则动态减去展开部分高度
//创建节点选择器,动态获取面板高度设置动画高度 var query = wx.createSelectorQuery(); query.select('#收缩栏面板展开部分容器id').boundingClientRect() query.exec(function (res) { //res[0].height 为获取的收缩栏面板展开部分的高度 finalHeight = that.data.swiperHeight - res[0].height ; that.setData({ 'isToggle' : !that.data.isToggle , 'swiperHeight' : finalHeight }) })