小程序轮播图自适应问题

时间:2018-12-03 14:12:05       编辑:echeverra


首先看效果图,针对不同的轮播图大小都可以适应。

swiper6.gif


代码:

  <!--index.wxml-->
<view class='content'>
    <swiper indicator-dots="{{indicatorDots}}"
        autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" style="height:{{imgHeights[current]}}px" bindchange='bindchange'>
        <block wx:for="{{imgUrls}}" wx:key="{{index}}">
            <swiper-item><image src='{{item}}' data-id="{{index}}" bindload="imageLoad" /></swiper-item>
        </block>
    </swiper>
</view>


//index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
        indicatorDots: true,
        autoplay: true,
        interval: 5000,
        duration: 500,
      imgUrls: ['../../images/t1.png', '../../images/gs3.jpg', '../../images/t3.png', '../../images/t4.png'],
        //所有图片的高度
        imgHeights: [],
        //默认
        current: 0,
  },

    imageLoad: function(e) {
        //获取原图宽高
        var imgWidth = e.detail.width;
        var imgHeight = e.detail.height;
        //原图宽高比
        var radio = imgWidth / imgHeight;
        //计算自适应后的图片高度,并放到数组中
        var imgHeight = this.data.viewWidth/radio;
        var imgHeights = this.data.imgHeights;
        imgHeights[e.target.dataset.id] = imgHeight;
        this.setData({
            imgHeights: imgHeights
        });
    },

    bindchange: function(e) {
        this.setData({
            current: e.detail.current
        });
    },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
      wx.getSystemInfo({
          success: res => {
              this.setData({
           //获取屏幕宽度
                  viewWidth: res.windowWidth
              });
          }
      })
  },
})


思路:

为每个轮播图片重新定义高度,计算图片的宽高比,在根据屏幕宽度,算出图片自适应的高度,放到一个数组中,轮播的图片通过id下标获取其高度即可


分析:

wxml部分直接使用内部的swiper小组件,分别绑定bindchange和bindload方法。

js部分首先onload方法获取屏幕宽度viewWidth。

bindchange获取轮播的id

最重要的就是imageload方法,首先获取原图片的宽高,并计算宽高比。然后算出自适应的图片高度,全部放到imgHeights数组中,滚动到哪个图片,就用其id在imgHeights数组中对应下标取值即可。