微信小程序之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 })
  },
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值