一、概述
小程序瀑布流是一個非常流行的UI組件,它可以顯示成行的矩形元素,並在不同的大小之間分配空間。這種布局模式可以非常好地利用空間,同時也可以讓用戶更好地找到他們的興趣點。
小程序瀑布流實現的基本原理是將每個元素歸為一定數量的列,然後將它們向下堆疊在一起,在每個瀑布流的列中平均分配元素。
二、實現步驟
1. 定義數據結構
interface IItem {
id: number | string;
width: number;
height: number;
imgUrl: string;
remark: string;
}
2. 獲取數據
Page({
data: {
items: [],
columns: 2,
},
onLoad: function () {
// 獲取數據
wx.request({
url: 'https://xxx.com/api/items',
success: (res) => {
const items = res.data.items;
this.setData({
items,
});
},
});
},
});
3. 計算瀑布流元素
getColumns() {
const { windowWidth } = wx.getSystemInfoSync();
const itemWidth = 300;
const columns = Math.floor(windowWidth / itemWidth);
return columns;
}
processItems(items) {
const { columns } = this.data;
let columnHeights = new Array(columns).fill(0);
const processedItems = items.map((item) => {
const width = 150; // 根據實際需要設置元素寬度
const height = item.height / item.width * width; // 縮放高度
const column = columnHeights.indexOf(Math.min(...columnHeights));
const top = columnHeights[column];
const left = column * width;
columnHeights[column] += height;
return { ...item, width, height, top, left };
});
return processedItems;
}
4. 渲染元素
<view class="waterfall">
<view class="waterfall__item" wx:for="{{ items }}" wx:key="id" style="width:{{ item.width }}px; height:{{ item.height }}px; top:{{ item.top }}px; left:{{ item.left }}px;">
<image class="waterfall__img" src="{{ item.imgUrl }}" mode="aspectFill" lazy-load />
<text class="waterfall__remark">{{ item.remark }}</text>
</view>
</view>
三、實現效果
我們已經完成了瀑布流的實現,瞧瞧效果:
四、注意事項
1. 所有的元素寬度必須設置為相同的固定值。
2. 儘可能確保每個元素都有一個高度,否則可能會出現奇怪的布局問題。
3. 當您使用image標籤時,請確保提供width和height屬性,這將確保圖像載入完畢時布局正確。
4. 在渲染過程中請進行性能測試,以確保性能達到最佳狀態。
五、總結
小程序瀑布流是一個非常實用的UI組件,可以在小程序中展示更好的信息,受到了用戶的喜歡。實現起來非常簡單,只需要確定每列的寬度,然後計算元素位置即可。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/233666.html