uniapp 瀑布流实现:代码示例与原理详解
<template>
<view class='waterfall'>
<view v-for='(item, index) in list' :key='index' class='waterfall-item' :style='{height: item.height + 'px'}'>
{{ item.text }}
</view>
</view>
</template>
<script>
export default {
data() {
return {
list: [
{ text: 'item1', height: 200 },
{ text: 'item2', height: 150 },
{ text: 'item3', height: 180 },
{ text: 'item4', height: 220 },
{ text: 'item5', height: 170 },
{ text: 'item6', height: 190 },
{ text: 'item7', height: 160 },
{ text: 'item8', height: 210 },
{ text: 'item9', height: 200 },
{ text: 'item10', height: 180 },
{ text: 'item11', height: 190 },
{ text: 'item12', height: 170 },
{ text: 'item13', height: 220 },
{ text: 'item14', height: 150 },
{ text: 'item15', height: 200 },
{ text: 'item16', height: 180 },
{ text: 'item17', height: 190 },
{ text: 'item18', height: 170 },
{ text: 'item19', height: 220 },
{ text: 'item20', height: 150 },
]
}
},
mounted() {
this.initWaterfall();
},
methods: {
initWaterfall() {
const waterfall = this.$refs.waterfall;
let columnCount = 2; //瀑布流列数
let itemWidth = (100 / columnCount) + '%'; //每列宽度
let itemHeightArr = new Array(columnCount).fill(0); //每列高度数组
for (let i = 0; i < this.list.length; i++) {
let item = this.list[i];
let minHeight = Math.min(...itemHeightArr); //获取最小高度
let minIndex = itemHeightArr.indexOf(minHeight); //获取最小高度索引
let itemTop = minHeight;
let itemLeft = (minIndex * (100 / columnCount)) + '%';
itemHeightArr[minIndex] += item.height;
item.top = itemTop + 'px';
item.left = itemLeft;
item.width = itemWidth;
}
this.list = JSON.parse(JSON.stringify(this.list)); //强制更新视图
},
}
}
</script>
<style>
.waterfall {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.waterfall-item {
position: relative;
margin-bottom: 20px;
}
</style>
<p>在这个示例中,我们首先定义了一个数组list,其中每个元素包含一个文本和高度属性。在mounted钩子函数中,我们调用了initWaterfall方法,该方法使用refs属性获取水瀑流容器的引用,然后使用columnCount变量定义列数和itemWidth变量定义每列宽度。</p>
<p>接下来,我们定义了一个itemHeightArr数组,该数组将每个列的高度设置为0,并遍历list数组中的每个元素。对于每个元素,我们使用Math.min()方法获取最小高度,并使用indexOf()方法获取最小高度的索引。然后,我们根据最小高度和索引计算出该元素的top和left属性,并更新itemHeightArr数组中对应列的高度。最后,我们将这些计算出的属性(width, top, left)赋值给每个元素,并强制更新视图。</p>
<p>最后,我们在样式中设置了.waterfall和.waterfall-item的样式,以实现瀑布流的效果。</p>
原文地址: https://www.cveoy.top/t/topic/lUSt 著作权归作者所有。请勿转载和采集!