5分钟教你搞定瀑布流样式

首先,我们来讲一下什么是瀑布流嘞?在某些个以图片为主的网站中,单一的布局那什么来吸引眼球,当然是尽量炫酷的布局了。瀑布流又称瀑布流式布局, 是现在流行的一种布局方式。知道了这些,那瀑布流布局实现的原理是什么呢?

关于瀑布流算法

此时,可以放在第一行的图片已经就绪,分别为图片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>

在日常生活中,我们还可以见到图片宽度不一,高度相同的情况,大家可以想一下怎么才能够实现~ 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值