天天看點

微信小程式中swiper元件高度根據圖檔自适應

wxml:

<!-- banner圖 -->
    <swiper style="height:{{imgHeight[current]}}rpx;" bindchange="bindchange">
      <block wx:for="{{imgUrls}}" wx:key="that">
        <swiper-item>
          <image src="{{item.img_url+webp}}" class="slide-image" mode='aspectFill' data-url="{{item.link}}" bindload="imageLoad" bindtap='goto' data-id="{{index}}" />
        </swiper-item>
      </block>
    </swiper>
           

wxss::由于swiper的高度在變化,是以需要加一個過渡動畫。

.swiper-box {
  position: relative;
  transition: height ease-out 0.2s; 
}

.slide-image {
  width: 100%;
  height: 100%;
}
           

js:

data: {
    //所有圖檔的高度  
    imgHeight: [],
    //圖檔寬度 
    imgwidth: 750,
    //預設  
    current: 0
  },
imageLoad: function (e) {//擷取圖檔真實寬度  
    var imgwidth = e.detail.width,
      imgheight = e.detail.height,
      //寬高比  
      ratio = imgwidth / imgheight;
    //計算的高度值  
    var viewHeight = 750 / ratio;
    var imgHeight= this.data.imgHeight;
    //把每一張圖檔的對應的高度記錄到數組裡  
    imgHeight[e.target.dataset.id] = viewHeight;
    this.setData({
      imgHeight
    })
  },
  bindchange: function (e) {
    this.setData({ 
        current: e.detail.current
     })
  },