要求: (頂部廣告欄 )
改變swiper組件的固定高度,使之隨內(nèi)部每張圖片的高度做自適應(yīng)
原理:
圖片加載完之后,獲取圖片的原始寬高,根據(jù)寬高比,計算出適應(yīng)后的寬高,如果是適應(yīng)屏幕寬度的話,就用到 wx.getSystemInfo() 方法設(shè)備的信息,并保存到一個數(shù)組中,(因為加載的原因不能用push,只能根據(jù)索引),切換時監(jiān)聽當(dāng)前顯示的圖片,根據(jù)其索引找到對應(yīng)的高度,并賦值給組件即可。
wxml:
<view class='swiper'> <swiper indicator-dots="{{indicatorDots}}" vertical="{{vertical}}" autoplay="{{autoplay}}" duration="{{duration}}" interval='{{interval}}' bindchange="bindchange" circular="{{circular}}" style="height:{{imgheights[current]}}rpx;"> <block wx:for='{{imgList}}' wx:key="{{index}}"> <swiper-item> <image src="{{item}}" data-id='{{index}}' class="slide-image" mode="widthFix" bindload="imageLoad"/> </swiper-item> </block> </swiper> </view>
wxss:
.swiper image { width: 100%; height: auto; }
js:
data: { //圖片地址 imgList: ['/images/wyh-img_bg.png', '/images/wyh-img8.png', '/images/wyh-img_shop1.png', '/images/wyh-img_bg1.png'], //是否采用銜接滑動 circular: true, //是否顯示畫板指示點 indicatorDots: false, //選中點的顏色 indicatorcolor: "#000", //是否豎直 vertical: false, //是否自動切換 autoplay: true, //自動切換的間隔 interval: 2500, //滑動動畫時長毫秒 duration: 100, //所有圖片的高度 imgheights: [], //圖片寬度 imgwidth: 750, //默認 current: 0 }, imageLoad: function (e) {//獲取圖片真實寬度 var imgwidth = e.detail.width, imgheight = e.detail.height, //寬高比 ratio = imgwidth / imgheight; console.log(imgwidth, imgheight) //計算的高度值 var viewHeight = 750 / ratio; var imgheight = viewHeight; var imgheights = this.data.imgheights; //把每一張圖片的對應(yīng)的高度記錄到數(shù)組里 imgheights[e.target.dataset.id] = imgheight; this.setData({ imgheights: imgheights }) }, bindchange: function (e) { // console.log(e.detail.current) this.setData({ current: e.detail.current }) },
效果圖: