Realize waterfall flow

Suppose 3 sets of pictures need to be loaded, and the picture heights are respectively

[20,10,30,40,50]

[60,90,70,80,100]

[100,100,100,100,100]

For the first row

The first row can be displayed directly, the current height array is [20,10,30,40,50]

For the second row

Consider the first one, height 60, and the minimum height of the previous row is 10, in the second column, so arrange this to the second column and update the height array to [20, 10+60, 30, 40, 50]

The second one, the height is 90, and the minimum height is now 20, which is in the first column, so arrange this to the first column and update the height array to [20+90, 70, 30, 40, 50]

The third one, height 70, now the minimum height is 30, in the third column, so arrange this to the third column, update the height array to [110, 70, 30+70, 40, 50]

....analogy

Sample code


      for (let i = 0; i < 15; i++) { //先定它个15个div
        var div = document.createElement("div");
        div.className = "item";
        div.style.height = i * 10 + 10 + "px"; //假设图片高度,要替换成实际图片高度 。
        document.body.appendChild(div);
      }
      var heightArray = [], //存储每列的高度。
        columns = 5; //假设为5列;
      for (let i = 0; i < 15; i++) {
        // 遍历所有div,对他们设置left和top值
        var currentDiv = document.getElementsByClassName("item")[i];
        if (i < columns) { //i<columns说明为第一排
          currentDiv.style.top = 0; //第一排top值为0
          currentDiv.style.left = i * 100 + "px"; // 第一张left:0,第二张left:100...
          heightArray[i] = currentDiv.offsetHeight; // 第1排直接设置
        } else {// 非第1排
          var minHeight = Math.min.apply(null, heightArray); //找到高度最小值
          var minIndex = heightArray.indexOf(minHeight); //找到最小值所在列
          currentDiv.style.top = minHeight + "px"; // 设置top值
          currentDiv.style.left = minIndex * 100 + "px"; //设置left值
          heightArray[minIndex] += currentDiv.offsetHeight; // 更新高度数组。

        }
      }

css:

 body {
        position: relative;
      }
      .item {
        margin: 20px;
        width: 100px;
        border: 1px solid red;
        position: absolute;
        box-sizing: border-box;
      }

effect:

Random height:

 

 

 

Guess you like

Origin blog.csdn.net/illusion_melody/article/details/84259142