要求: (頂部廣告欄 )小程序
改變swiper組件的固定高度,使之隨內部每張圖片的高度作自適應微信小程序
原理: 數組
圖片加載完以後,獲取圖片的原始寬高,根據寬高比,計算出適應後的寬高,若是是適應屏幕寬度的話,就用到 wx.getSystemInfo() 方法設備的信息,並保存到一個數組中,(由於加載的緣由不能用push,只能根據索引),切換時監聽當前顯示的圖片,根據其索引找到對應的高度,並賦值給組件便可。微信
wxml:xss
<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:ide
.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; //把每一張圖片的對應的高度記錄到數組裏 imgheights[e.target.dataset.id] = imgheight; this.setData({ imgheights: imgheights }) }, bindchange: function (e) { // console.log(e.detail.current) this.setData({ current: e.detail.current }) },
效果圖:this