在使用小程序轮播图过程中,发现轮播滑动高度是固定的,当活动到第二页时,会出现很大一块空白内容,视觉效果比较差
实现效果:
第一页:

第二页:

轮播高度计算
每页轮播高度 = 当页图片总高度 + 总间距
图片设计图显示尺寸(px):105 × 108
设计图标准尺寸(px):375
屏幕宽度(px):screenWidth
屏幕与设计图分辨率比率: ratio = screenWidth / 375
图片实际展示尺寸:imgWidth = 105 * ratio, imgHeight = 108 * ratio
已知图片间距 space = 12 px
每页轮播图片展示行数 row
图片总高度 = imgHeight * row
总间距 = (row - 1) * 12px
① 获取screenWidth,计算屏幕与设计图分辨率比率 ratio
javascript
let windowInfo = wx.getWindowInfo()
let ratio = windowInfo.screenWidth / 375
this.setData({
ratio: ratio
})
② 计算轮播图片展示行数 row,设置首页轮播高度swiperHeight
javascript
let imgHeight = 108
let row = Math.ceil(this.data.list[0].length / 3) // 计算单页轮播行数
let swiperHeight = row * imgHeight * + (row - 1) * 12
this.setData({
currentSwiper: 0, // 默认轮播下标
swiperHeight: swiperHeight // 首页轮播高度
})
html
<swiper
class="my-swipe"
indicator-dots="{{false}}"
interval="{{5000}}"
style="height: {{swiperHeight}}px;"
current="{{currentSwiper}}"
bindchange="onChange"
>
</swiper>
③ 轮播图滑动时,重新计算高度
javascript
onChange() {
let currentIndex = el.detail.current
let row = Math.ceil((this.data.list[currentIndex].length / 3))
let swiperHeight = row * 108 * this.data.ratio + (12 * (row - 1))
this.setData({
swiperHeight: swiperHeight
})
}