<template>
   <div class="container">
    <div class="waterfall" ref="waterfall">
         <div class="img-item"  v-for="index in 17" :key="index">
            <span class="index">{{index}} </span>
            <img :src="`https://shuliqi.github.io/xiaozhan/${index +1}.jpeg`"/>
          </div>
    </div>
  </div>
</template>

<script>
export default {
  mounted () {
    this.$nextTick(() => {
      this.waterFall()
    })
  },
  methods: {
    waterFall() {
      var items = document.getElementsByClassName('img-item');
      if (items.length === 0) return;
      //定义间隙10像素
      var gap = 20;
      //首先确定列数 = 页面的宽度 / 图片的宽度
      var pageWidth = this.$refs.waterfall.offsetWidth;

      var itemWidth = items[0].offsetWidth;
      var columns = parseInt(pageWidth / (itemWidth + gap));

      var arr = [];//定义一个数组,用来存储元素的高度
      for(var i = 0;i < items.length; i++){
          if(i < columns) {
              //满足这个条件则说明在第一行,文章里面有提到
              items[i].style.top = 0;
              items[i].style.left = (itemWidth + gap) * i + 'px';
              arr.push(items[i].offsetHeight);
          }else {
              //其他行,先找出最小高度列,和索引
              //假设最小高度是第一个元素
              var minHeight = arr[0];
              var index = 0;
              for(var j = 0; j < arr.length; j++){//找出最小高度
                if(minHeight > arr[j]){
                    minHeight = arr[j];
                    index = j;
                } 
              }
              //设置下一行的第一个盒子的位置
              //top值就是最小列的高度+gap
              items[i].style.top = arr[index] + gap + 'px';
              items[i].style.left = items[index].offsetLeft + 'px';

              //修改最小列的高度
              //最小列的高度 = 当前自己的高度 + 拼接过来的高度 + 间隙的高度
              arr[index] = arr[index] + items[i].offsetHeight + gap;
          }
      }
    },
    
  }

};
</script>

<style lang="scss">
.container {
  width: 420px;
  height: 800px;
  margin: 0 auto;
  overflow-x: hidden;
  overflow-y: scroll;
  border: 1px solid #e6e6e6;
  .waterfall {
    width: 450px;
    position: relative;
    .img-item {
      position: absolute;
      width: 200px;
      box-sizing: border-box;
      .index {
        position: absolute;
        margin-top: 20px;
        padding: 5px 10px;
        background: #000;
        color: #fff;
      }
      img {
        width: 100%;
      }
    }

  }
}
</style>

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.