1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > 微信小程序轮播图高度自适应代码

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

时间:2020-09-12 07:03:34

相关推荐

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

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

在微信小程序上实现图片自适应需要配合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"}

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

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});}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。