微信小程序轮播图高度自适应

图片自适应在网站上是内置好的,只需要设置宽度即可,但在微信小程序非要做一个封装,高度不是随宽度自适应,真是操蛋,不过谁叫在人家的平台的搞呢,还是不得不屈服于小马哥的淫威啊。。

在微信小程序上实现图片自适应需要配合javascript脚本,也就是需要动态计算才能实现,具体修改如下:

先看下view层是什么样的

<view class="zh-carousel" style="margin-top: {{carouselMarginTop}}rpx">
    <swiper indicator-dots="true" autoplay="true" interval="4000" duration="500" class="zh-swiper" style="height: {{carouselHeight}}px">
      <swiper-item class="zh-swiper-item" wx:for="{{carouselList}}" wx:key="index">
        <image src="{{ item.image }}" mode="widthFix" bindload="adaptCarouselHeight"></image>
      </swiper-item>
    </swiper>
</view>

因为设置了导航样式为自定义,所以需要给轮播图加个margin-top值 ,不然会被小程序功能按钮遮挡

{
  "usingComponents": {},
  "navigationStyle": "custom"
}

image.png

下面看下数据是如何计算的(注释很详细),如果不想细看的话,直接对着撸就行了

Page({
  data: {
    list: [],
    carouselList: [
      {image: '../../images/img-wx-gzh.png'},
    ],
    carouselMarginTop: 0, // 这两个初始值必须要设置
    carouselHeight: 0
  },
  onLoad: function() {
    this.adaptCarouselMarginTop(); // 适配轮播图外间距
  },
  // 适配轮播图外间距
  adaptCarouselMarginTop() {
    let systemInfo = wx.getSystemInfoSync(),
      pxToRpxScale = 750 / systemInfo.windowWidth, // px转换到rpx的比例
      ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale, // 状态栏高度
      navigationHeight = 44 * pxToRpxScale; // 导航高度,44是大概估值
    this.setData({
      carouselMarginTop: navigationHeight + ktxStatusHeight + 10 // 10是一个预估值,可根据呈现效果修改
    });
  },
  // 适应轮播图高度
  adaptCarouselHeight(e) {
    let imgWidth = e.detail.width, // 原图宽高
      imgHeight = e.detail.height,
      screenWidth = wx.getSystemInfoSync().screenWidth; // 手机屏幕宽度
    let ratio = (screenWidth - screenWidth/750*60) / imgWidth;
    this.setData({
      carouselHeight: imgHeight * ratio
    });
  }
}

欢迎关注:https://www.fenxianglu.cn/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天空还下着雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值