微信小程序之swiper組件高度自適應


微信小程序之swiper組件高度自適應

要求:頂部廣告欄

   改變swiper組件的固定高度,使之隨內部每張圖片的高度做自適應

原理: 

   圖片加載完之后,獲取圖片的原始寬高,根據寬高比,計算出適應后的寬高,如果是適應屏幕寬度的話,就用到 wx.getSystemInfo() 方法設備的信息,並保存到一個數組中,(因為加載的原因不能用push,只能根據索引),切換時監聽當前顯示的圖片,根據其索引找到對應的高度,並賦值給組件即可。

  

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;
    //把每一張圖片的對應的高度記錄到數組里  
    imgheights[e.target.dataset.id] = imgheight;
    this.setData({
      imgheights: imgheights
    })
  },
  bindchange: function (e) {
    // console.log(e.detail.current)
    this.setData({ current: e.detail.current })
  },

效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM