微信小程序瀑布流布局可以让我们在展示图片、商品等方面有更丰富的呈现方式。本文将从选取图片源、图片宽度处理、动态设置页面高度、滚动加载等几个方面为大家介绍微信小程序瀑布流布局的实现技巧。
一、选取图片源
在实现瀑布流布局时,必不可少的要素就是选取响应式图片。我们可以通过API调用网络上的图片,也可以在本地保存一定规格比例的图片,这样利用CSS设置大小可以自适应各种尺寸。举个例子,从淘宝开放平台接口调用商品信息,我们需要获取到每个商品的信息,其中最重要的信息就是商品图片的链接。根据链接我们可以抓取图片生成响应式图片,以最大程度上提高图片加载速度,提高用户体验。
下面是微信小程序使用API获取网络图片的实现代码:
“`
wx.downloadFile({
url: ‘https://example.com/图片链接’,
success: function (res) {
if (res.statusCode === 200) {
console.log(‘下载图片成功’)
return res.tempFilePaths
}
console.log(‘下载图片失败’)
}
})
“`
二、图片宽度处理
在瀑布流布局中,每个图片的宽度要需要保持一致,而高度是根据图片的实际高度自动计算。因此在处理宽度时,需要考虑到图片的数量不一定是偶数,需要在保持宽度一致的情况下,让左右两侧的图片宽度比较接近,最好不要出现左边很窄,右边很宽的情况。
下面是图片宽度处理的示例代码:
“`
const screenWidth = wx.getSystemInfoSync().screenWidth;// 获取屏幕宽度
const styleList = []
const widths = [100, 200, 300, 400]// 定义瀑布流每个item的宽度,这里取4个不同大小的宽度值
for (let i = 0; i < 50; i++) {// 在循环中计算每个item的宽度和位置
let tempStyle = ''
if (i % 2 === 0) {
const width = widths[Math.floor(Math.random() * widths.length)]
tempStyle = `width: ${width}px;position: absolute;left: ${i % 2 === 0 ? screenWidth / 2 – width / 2 : screenWidth / 2}px;top: ${i / 2 * 200}px;`
} else {
const width = widths[Math.floor(Math.random() * widths.length – 1) + 1]
tempStyle = `width: ${width}px;position: absolute;left: ${i % 2 === 0 ? screenWidth / 2 : screenWidth / 2 – width / 2}px;top: ${Math.ceil(i / 2 – 1) * 200}px;`
}
styleList.push(tempStyle)
}
console.log(styleList)
“`
三、动态设置页面高度
瀑布流布局中,需要根据图片高度动态设置页面高度,避免出现空白或者重叠的情况。通过遍历图片高度获取每一列的高度,再取出高度最大的那一列作为页面高度。
下面是动态设置页面高度的示例代码:
“`
let heightList = []
let column = 3
let index = 0
for (let i = 0; i {
heightList[index] = heightList[index] ? heightList[index] + res.height : res.height
if (i === 49) {//最后一个元素,循环结束后设置页面高度
let max = heightList[0]
for (let j = 0; j max) {
max = heightList[j]
}
}
let scrollTop = e.detail.scrollTop
this.setData({
scrollTop: scrollTop,
pageHeight: max * (Math.ceil(i / column))
})
}
if ((i + 1) % column === 0) {
index = 0
} else {
index++
}
}).exec()
}
“`
四、滚动加载
虽然瀑布流布局可以在页面上优美地展示出图片,但是由于图片的数量可能会很多,一次性全部加载也容易导致页面卡顿,甚至崩溃。因此采用滚动加载的方式,让用户在滚动页面到底部时再加载部分图片,这样就不会一下子把所有图片都加载出来。
下面是滚动加载的示例代码:
“`
onPageScroll: function (e) {
const scrollTop = e.scrollTop
const windowHeight = wx.getSystemInfoSync().windowHeight
const pageHeight = this.data.pageHeight
if (scrollTop + windowHeight > pageHeight – 5) {//滚动到底部时,设置isLoadMore为true,加载新数据
if (!this.data.isLoadMore && this.data.hasMoreData) {
this.setData({
isLoadMore: true
})
wx.showLoading({
title: ‘加载中’
})
setTimeout(() => {
this.setData({
isLoadMore: false,
list: this.data.list.concat([{ url: ‘https://example.com/新的图片链接’ }])// 这里添加新图片地址,可以结合API实现
})
wx.hideLoading()
}, 2000)
}
}
}
“`
至此,我们通过选取图片源、图片宽度处理、动态设置页面高度、滚动加载等方面为大家介绍了微信小程序瀑布流布局的实现技巧,希望对大家有所帮助。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/296201.html