实现效果:swiper的高度每次都能以图片集中的最高图片(高宽比不超过1.6)为基准,其余图片在此高度中居中
最高图片 普通图片
参考:微信小程序之swiper组件高度自适应 - 梦幻飞雪 - 博客园 (cnblogs.com)
wxml:
<!-- 图片集 -->
<swiper indicator-dots indicator-color="rbga(255,255,255,0.5)" indicator-active-color="#6495ED" circular class="swp" style="height:{{imgheight}}rpx;" >
<swiper-item wx:for="{{imgs}}" wx:key="index" class="item">
<image src="http://127.0.0.1:8000/media/{{item.img}}" bindload="imageLoad" mode="aspectFit"/>
</swiper-item>
</swiper>
wxss:
.swp{width:750rpx;height: auto;}
.swp .item{display:flex;}
.item image{margin:auto auto;width: 100%;height:100%;}
js:
data: {
imgs:[],
imgheight:750,
imgwidth:750,
ratio:0,
index:0
},
imageLoad:function(e){
var that = this
that.data.index++
var imgwidth = e.detail.width
var imgheight = e.detail.height
var ratio = imgheight/imgwidth
//依次比较,获取高度最高图片的ratio
if(ratio>that.data.ratio){
that.setData({
ratio:ratio
})
}
var length = that.data.imgs.length
// 当图片全部加载完;此时的ratio是所有图片中最大的
if(that.data.index==length){
var imgheight
//限制swiper高度,ratio最高不得超过1.6
if(that.data.ratio<1.6){
imgheight = 750*that.data.ratio
}
else{
imgheight = 1200
}
that.setData({
imgheight:imgheight
})
console.log(that.data.imgheight)
}
},