在开发图片展示类的小程序时,swiper组件是非常好用的,但是其中也有些“坑”,等着你去踩。好啦,我已经踩过了,给各位一个借鉴吧~
效果:
##1.使用
首先在页面的.wxml文件内使用swiper组件
wxml:
<view class="swiperFather">
<swiper class="swiper" bindchange="getImgIndex">
<!--wx:for渲染的是需展示的图片列表-->
<swiper-item class="swiperItem" wx:for="{{imgList}}">
<!--mode='aspectFit',设置很重要,保持纵横比缩放图片,使图片的长边能完全显示出来。可以完整地将图片显示出来。你可以根据需要选择对应的状态-->
<image class="img" src="{{item}}" mode='aspectFit' />
</swiper-item>
</swiper>
</view>
##2.swiper高度自适应
因为微信swiper高度是固定的150px,图片就不能显示完全,在网上搜索出来的解决方案都是用js获取图片的高度,再动态设置swiper元素的高度,很复杂我们完全可以用css的方式解决!
wxss:
/* 页面高度设为100vh,撑开父元素高度*/
page{
height:100vh
}
/*设置swiper父元素高度为100%占满整个显示界面 */
.swiperFather{
height:100%
},
.swiper{
/* 整体高度 - 底部固定的高度 = swiper高度*/
height: calc(100% - 100px);
}
.swiperItem{
/* 图片居中显示,swiper是紧贴在头部位置显示的,图片高度不够的话下面空白处很多,显示很丑,这样居中展示更好看*/
display:flex;
align-items:center;
},
.img{
height:100%/* 根据父元素高度自适应显示*/
}
好啦~这样我们就实现了文章开头的展示效果.
##3.获取当前图片index
如果需要显示当前图片的index,给swiper绑定bindchange事件,再通过函数获取e.detail.current就行啦!
js:
page({
data:{
imgIndex:null
},
getImgIndex:function(e){
this.setData({
<!--这里current+1是因为微信默认 current = 0 ,为了显示图片当前张数,所以加1-->
imgIndex:e.detail.current+1
})
}
})