微信小程序swiper图片尺寸_微信小程序 - swiper 高度自适应

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-29 15:24   11   0

我这边开发用的是 wepy,代码风格跟小程序原生的不太一样,下面代码是依照小程序的代码风格整理之后的,可能有不同或遗漏的地方,但这都不重要,注意领会精神!

原理:

获取设备宽度

获取 swiper 内的图片宽高,计算宽高比

根据宽高比计算出图片宽度100%(屏幕宽度)时图片的高度 imgHeight

由于多张图片可能高度不一致,所以将所有的 imgHeight 放入一个数组,swiper 滑动时就将当前图片的 imgHeight 赋值给 swiper。

// wxml

// js

data: {

windowWidth: 0,

imgUrls: [...],

imgsHeight: [],

current: 0,

imgWidth: 750

}

// 每张图片加载完成会执行 imageload 方法

imageLoad: function(e) {

// 获取图片宽高比

const ratio = e.detail.width / e.detail.height

// 按照宽高比计算图片宽度 100% 时的高度

const imgHeight = this.windowWidth / ratio

// 把每一张图片对应的高度记录到 imgsHeight 数组里

this.imgsHeight[e.target.dataset.id] = imgHeight

},

// swiper 绑定 bindchange 函数,用来获取 current 值,传入 data

bindchange: function(e) {

this.setData({

current: e.detail.current

})

}

onLoad() {

// 获取设备屏幕宽度

wx.getSystemInfo({

success: (res) => {

this.windowWidth = res.windowWidth

}

})

}

// wxss

.swiper image {

width: 100%;

height: 100%;

}

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP