微信小程序中使用swiper组件可以实现图片轮播效果,但是默认swiper高度是固定的150px,如果项目中图片大于固定高度就会被隐藏,所以本篇文章要实现轮播图片的高度自适应。
效果图:
wxml代码:
<swiper class="t-swiper" indicator-dots="{{indicatordots}}" indicator-active-color="{{color}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" style="height:{{height}}"> <block wx:for="{{img}}" wx:key=""> <swiper-item> <image src="{{item}}" mode="widthFix" bindload='goheight' /> </swiper-item> </block> </swiper>
wxss代码:
.t-swiper image { width: 100%; }
js代码:
Page({ data: { img: [ 'img/1.jpg', 'img/2.jpg', 'img/3.jpg' ], indicatordots: true, //是否显示面板指示点 autoplay: true, //是否自动切换 interval: 5000, //自动切换时间间隔 duration: 500, //滑动动画时长 color: '#ffffff', //当前选中的指示点颜色 height: '' //swiper高度 }, goheight: function (e) { var width = wx.getSystemInfoSync().windowWidth //获取可使用窗口宽度 var imgheight = e.detail.height //获取图片实际高度 var imgwidth = e.detail.width //获取图片实际宽度 var height = width * imgheight / imgwidth + "px" //计算等比swiper高度 this.setData({ height: height }) } })