小程序轮播图片高度自适应

微信小程序中使用swiper组件可以实现图片轮播效果,但是默认swiper高度是固定的150px,如果项目中图片大于固定高度就会被隐藏,所以本篇文章要实现轮播图片的高度自适应。

1.以最高的图片为基准(需要考虑图片全部一样的大小)

关于小程序轮播图自适应的问题,目前网上的资料不少,但是都是目前这种,不会随着图片的高度去变化。会以最高的一张图片高度为基准。正常的需求应该都能满足,但是现在的需求是需要随着图片的高度去改变。所以有了第二点

动态轮播图高度1.gif

<swiper  style="height:{{swiperHeight}}" class="t-swiper" indicator-dots="{{indicatordots}}" indicator-active-color="{{color}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}">
  <block wx:for="{{imgUrls}}" wx:key="index">
    <swiper-item>
      <image src="{{item}}" mode="widthFix" bindload='goheight' />
    </swiper-item>
  </block>
</swiper>
Page({
  data: {
    imgUrls: [
      'img/1.jpg',
      'img/2.jpg',
      'img/3.jpg'
    ],
    indicatordots:true,//是否显示面板指示点
    autoplay:true, //是否自动切换
    interval: 5000,//自动切换时间间隔
    duration: 500,  //滑动动画时长
    color:'#ffffff', //当前选中的指示点颜色
    swiperHeight:''//swiper高度
   
  },
  goheight:function (e) {
    var width = wx.getSystemInfoSync().windowWidth
    //获取可使用窗口宽度
    var imgheight = e.detail.height
    //获取图片实际高度
    var imgwidth = e.detail.width
    //获取图片实际宽度
    var height = width * imgheight / imgwidth +"px"
    //计算等比swiper高度
    this.setData({
      swiperHeight: height
    })
  }
})

2.以当前图片的高度为基准(完美实现)

动态轮播图高度.gif

<swiper style="height:{{imgheights[swiperCurrent]}};" indicator-dots="{{indicatorDots}}" autoplay="{{autoplay}}" interval="{{interval}}" duration="{{duration}}" indicator-active-color="{{bg}}">  
  <block wx:for="{{imgUrls}}" wx:for-item='item' wx:for-index='idx'>  
    <swiper-item>  
       //bindload是绑定图片加载的事件,记得给image加上mode=“widthFix”这个属性哦,
       //还有就是设置这个image 100%宽度
      //getswiperImgH 中打印 图片的 src 发现 顺序有时和图片真实的顺序是不一致,故加了一个参数
    	<image  style="height:{{imgheights[swiperCurrent]}};" bindload='getswiperImgH' data-idnex="{{idx}}" mode="widthFix"  src="{{item}}" class="slide-image"/>  
    </swiper-item>  
  </block>  
</swiper>  

Page({
  data: {
  	imgUrls: [
      'https://img3.doubanio.com/view/photo/l/public/p2494946035.webp',
      'http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg',
      'http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg',
    ],
    imgheights: [],
    swiperCurrent: 0
  },
   bindchange: function (e) {
     this.setData({
     		swiperCurrent:e.detail.current
     })
   },
   getswiperImgH(e){
   	 //获取当前屏幕的宽度
     let winWid = wx.getSystemInfoSync().windowWidth;   
     //图片高度
     let imgh = e.detail.height; 
     //图片宽度
     let imgw = e.detail.width;
     //计算的高度值
     let swiperH = winWid * imgh / imgw +'px'
     let imgheights=this.imgheights
     //把每一张图片的高度记录到数组里
     imgheights[e.currentTarget.dataset.index] = swiperH
     this.setData({
     		imgheights:imgheights
     })
   }
})
posted @ 2021-01-20 00:04  Leader755  阅读(775)  评论(0编辑  收藏  举报