微信小程序中使用swiper組件可以實現圖片輪播效果,但是默認swiper高度是固定的150px,如果項目中圖片大於固定高度就會被隱藏,所以本篇文章要實現輪播圖片的高度自適應。
1.以最高的圖片爲基準(需要考慮圖片全部一樣的大小)
關於小程序輪播圖自適應的問題,目前網上的資料不少,但是都是目前這種,不會隨着圖片的高度去變化。會以最高的一張圖片高度爲基準。正常的需求應該都能滿足,但是現在的需求是需要隨着圖片的高度去改變。所以有了第二點。
<swiper style="height:{{swiperHeight}}" class="t-swiper" indicator-dots="{{indicatordots}}" indicator-active-color="{{color}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}">
<block wx:for="{{imgUrls}}" wx:key="index">
<swiper-item>
<image src="{{item}}" mode="widthFix" bindload='goheight' />
</swiper-item>
</block>
</swiper>
Page({
data: {
imgUrls: [
'img/1.jpg',
'img/2.jpg',
'img/3.jpg'
],
indicatordots:true,//是否顯示面板指示點
autoplay:true, //是否自動切換
interval: 5000,//自動切換時間間隔
duration: 500, //滑動動畫時長
color:'#ffffff', //當前選中的指示點顏色
swiperHeight:''//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({
swiperHeight: height
})
}
})
2.以當前圖片的高度爲基準(完美實現)
<swiper style="height:{{imgheights[swiperCurrent]}};" indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" indicator-active-color="{{bg}}">
<block wx:for="{{imgUrls}}" wx:for-item='item' wx:for-index='idx'>
<swiper-item>
//bindload是綁定圖片加載的事件,記得給image加上mode=“widthFix”這個屬性哦,
//還有就是設置這個image 100%寬度
//getswiperImgH 中打印 圖片的 src 發現 順序有時和圖片真實的順序是不一致,故加了一個參數
<image style="height:{{imgheights[swiperCurrent]}};" bindload='getswiperImgH' data-idnex="{{idx}}" mode="widthFix" src="{{item}}" class="slide-image"/>
</swiper-item>
</block>
</swiper>
Page({
data: {
imgUrls: [
'https://img3.doubanio.com/view/photo/l/public/p2494946035.webp',
'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg',
],
imgheights: [],
swiperCurrent: 0
},
bindchange: function (e) {
this.setData({
swiperCurrent:e.detail.current
})
},
getswiperImgH(e){
//獲取當前屏幕的寬度
let winWid = wx.getSystemInfoSync().windowWidth;
//圖片高度
let imgh = e.detail.height;
//圖片寬度
let imgw = e.detail.width;
//計算的高度值
let swiperH = winWid * imgh / imgw +'px'
let imgheights=this.imgheights
//把每一張圖片的高度記錄到數組裏
imgheights[e.currentTarget.dataset.index] = swiperH
this.setData({
imgheights:imgheights
})
}
})