A method to set the adaptive height of the pictures in the swiper carousel of the WeChat applet

A method to set the adaptive height of the pictures in the swiper carousel of the WeChat applet

The carousel image in the mini program is very simple, but the only flaw is that the swiper has a fixed height of 150px (width of 320px), so if the incoming image is larger than this height, it will be hidden. So how to adapt images to different resolutions is a very important issue.

Insert image description here

One idea is to get the screen width, get the width and height of the picture, and then set the height of the swiper under the current screen width in proportion.

1. wxml structure

<swiper autoplay circular indicator-dots style="height: { 
        { 
        swiperHeight}};">
    <swiper-item wx:for="{
     
     {swiperData}}" wx:key="id">
      // 注意设置 mode="widthFix" 和 style="width: 100%;"
      <image mode="widthFix" src="{
     
     {item.image_src}}" style="width: 100%;" bindload="computeImgHeight"></image>
    </swiper-item>
  </swiper>

2. js file

Page({
    
    
    data: {
    
    
        swiperHeight: "",     // swiper的高度
    },
    computeImgHeight(e) {
    
    
    var winWid = wx.getSystemInfoSync().windowWidth;      //获取当前屏幕的宽度
    var imgh=e.detail.height;                //图片高度
    var imgw=e.detail.width;
    var swiperH = winWid * imgh / imgw + "px"            //等比设置swiper的高度。  
    //即 屏幕宽度 / swiper高度 = 图片宽度 / 图片高度  -->  swiper高度 = 屏幕宽度 * 图片高度 / 图片宽度
    this.setData({
    
    
      swiperHeight: swiperH		//设置swiper高度
    })
  }
})

3. Effect

Insert image description here

Guess you like

Origin blog.csdn.net/Alan_Walker688/article/details/128317706