微信小程序-横向轮播时,轮播高度随内容高度动态撑开

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

第一页:

第二页:

轮播高度计算

复制代码
每页轮播高度 = 当页图片总高度 + 总间距

图片设计图显示尺寸(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
	})
}
相关推荐
WangHappy1 天前
不写 Canvas 也能搞定!小程序图片导出的 WebView 通信方案
前端·微信小程序
小时前端1 天前
微信小程序选不了本地文件?用 web-view + H5 一招搞定
前端·微信小程序·uni-app
icebreaker2 天前
Weapp-vite:原生模式之外,多一种 Vue SFC 选择
前端·vue.js·微信小程序
icebreaker2 天前
重走 Vue 长征路 Weapp-vite:编译链路与 Wevu 运行时原理拆解
前端·vue.js·微信小程序
大米饭消灭者5 天前
Taro是怎么实现一码多端的【底层原理】
微信小程序·taro
FliPPeDround6 天前
Vitest Environment UniApp:让 uni-app E2E 测试变得前所未有的简单
微信小程序·e2e·前端工程化
FliPPeDround6 天前
微信小程序自动化的 AI 新时代:wechat-devtools-mcp 智能方案
微信小程序·ai编程·mcp
吴声子夜歌6 天前
小程序——布局示例
小程序
码云数智-大飞6 天前
如何创建自己的小程序,码云数智与有赞平台对比
微信小程序
luffy54596 天前
微信小程序页面使用类似filter函数的wxs语法
微信小程序·小程序