首先,我们来讲一下什么是瀑布流嘞?在某些个以图片为主的网站中,单一的布局那什么来吸引眼球,当然是尽量炫酷的布局了。瀑布流又称瀑布流式布局, 是现在流行的一种布局方式。知道了这些,那瀑布流布局实现的原理是什么呢?
关于瀑布流算法
此时,可以放在第一行的图片已经就绪,分别为图片1234,这时候第一行已经放满,5号图片需要找到合适自己的位置,我们很清楚的看到,2号下面最最合适了,所以5号就登场啦
6号7号...都会依次找到属于自己的位置
知道它是怎么回事儿之后,我们转换成代码看下(vue3+typescript实现)
<template>
<div
v-for="item in imgList"
:key="item"
class="item">
<!-- 循环遍历展示图片 -->
<img :alt="item" :src="require('../assets/img/' + item + '.jpeg')" width="300" :height="imgHeight[item]">
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted } from 'vue';
export default defineComponent({
name: 'Home',
setup() {
const imgList = [];
// 设置图片的高度
const imgHeight = {
1: 150,
2: 200,
3: 500,
4: 250,
5: 300,
6: 400,
7: 500,
8: 100
};
// 随机生成30个图片
for (let index = 0; index < 30; index++) {
imgList.push(Math.floor((Math.random() * 8) + 1));
}
onMounted(() => {
// 每行能放几张图片
const num = Math.floor(document.body.clientWidth / 300);
const items = document.getElementsByClassName('item');
// heightList包含height字段(表示高度),columns字段(表示哪一列)
const heightList: any = [];
const gap = 10; // 图片缝隙
for (let index = 0; index < items.length; index++) {
if (index < num) {
(items[index] as any).style.top = 0;
(items[index] as any).style.left = index * (300 + gap) + 'px';
heightList.push({
height: (items[index] as any).offsetHeight,
columns: index % num
});
} else {
// 找到最小数的索引
const findIndex = heightList.findIndex((i: any) => i.height === Math.min(...heightList.map((it: any) => it.height)));
(items[index] as any).style.top = heightList[findIndex].height + gap + 'px';
(items[index] as any).style.left = heightList[findIndex].columns * (300 + gap) + 'px';
heightList[findIndex].height = heightList[findIndex].height + (items[index] as any).offsetHeight + gap;
}
}
});
return {
imgList,
imgHeight
};
}
});
</script>
<style>
.home {
position: relative;
}
.item {
display: inline-block;
position: absolute;
}
</style>
在日常生活中,我们还可以见到图片宽度不一,高度相同的情况,大家可以想一下怎么才能够实现~