微信小程序swiper高度自适应
时间: 2023-09-14 18:12:53 浏览: 476
微信小程序的swiper组件默认是根据图片的高度来设置swiper的高度的,所以如果要实现swiper高度自适应的效果,可以采用以下几种方式:
1. 使用image组件获取图片的高度:在swiper-item中使用image组件来展示图片,并设置mode为aspectFill,然后通过image组件的bindload事件获取到图片加载后的高度,并将该高度动态赋值给swiper组件的高度属性。例如:
```html
<swiper style="height:{{swiperHeight}}px;" current="{{current}}">
<block wx:for="{{imageList}}" wx:key="*this">
<swiper-item>
<image src="{{item}}" mode="aspectFill" bindload="getImageHeight"></image>
</swiper-item>
</block>
</swiper>
```
```javascript
Page({
data: {
swiperHeight: 0,
current: 0,
imageList: ['image1.png', 'image2.png', 'image3.png'],
},
getImageHeight: function(e) {
const { index, height } = e.currentTarget.dataset;
this.setData({
swiperHeight: height
});
}
})
```
2. 使用wx.createSelectorQuery获取图片高度:在onLoad生命周期函数中使用wx.createSelectorQuery来获取图片的高度,并将该高度动态赋值给swiper组件的高度属性。例如:
```javascript
Page({
data: {
swiperHeight: 0,
current: 0,
imageList: ['image1.png', 'image2.png', 'image3.png'],
},
onLoad: function() {
const query = wx.createSelectorQuery();
query.select('.swiper-item-image').boundingClientRect(res => {
this.setData({
swiperHeight: res.height
});
}).exec();
}
})
```
```html
<swiper style="height:{{swiperHeight}}px;" current="{{current}}">
<block wx:for="{{imageList}}" wx:key="*this">
<swiper-item>
<image class="swiper-item-image" src="{{item}}" mode="aspectFill"></image>
</swiper-item>
</block>
</swiper>
```
以上两种方式都可以实现swiper高度自适应的效果,你可以根据自己的实际需求选择其中一种方法来实现。