瀑布流佈局

weixin_34236869發表於2018-02-05

這是html,首先先定義一個容器ct,裡面的div模擬照片,每張照片的寬度一樣,高度不一樣

<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
<div class="ct">
  <div class="item h1">1</div>
   <div class="item h2">2</div>
   <div class="item h3">3</div>
   <div class="item h2">4</div>
   <div class="item h1">5</div>
   <div class="item h3">6</div>
   <div class="item h2">7</div>
   <div class="item h2">8</div>
   <div class="item h3">9</div>
   <div class="item h1">10</div>
   <div class="item h1">11</div>
   <div class="item h2">12</div>
   <div class="item h2">13</div>
   <div class="item h1">14</div>
   <div class="item h2">15</div>
</div>
</body>
</html>
function waterFull() {
  var $ctWidth = $('.ct').width(), //獲取容器寬度
    $nodeWidth = $('.item').width(), //獲取每個節點寬度
    colLength = parseInt($ctWidth / $nodeWidth), //獲取頁面每一行數量
    itemArr = []; //初始化陣列
  for (var i = 0; i < colLength; i++) {
    itemArr[i] = 0; //遍利陣列
  }
  $('.item').each(function() {
    var minValue = Math.min.apply(null, itemArr); //獲取最小值
    var minIndex = itemArr.indexOf(minValue); //獲取最小的索引值
    $(this).css({ //定義位置
      top: itemArr[minIndex], //
      left: $(this).outerWidth(true) * minIndex
    });
    itemArr[minIndex] += $(this).outerHeight(true);
  });
}

1、定義好瀑布流函式,
2、然後獲取容器的寬度,和每個節點的寬度,因為我們要得到容器裡面有幾列,初始化陣列,讓item為0
3、遍歷節點陣列
4、通過Math.min.apply(null, itemArr)獲取到最小值,和最小值的下標
5、最上面開始擺放最小值的下標對應的值,往左偏移的距離是最小的那個的寬度
6、陣列的最小值的高度變化

最後還可以優化下程式碼,將程式碼進行封裝

var Render = (function () {
      function init() {
        waterFull();
        $(window).resize(function () { //視窗尺寸每次變化,執行一次瀑布流
          waterFull();
        });
      }
      function waterFull() {
        var $ctWidth = $('.ct').width(),//獲取容器寬度
          $nodeWidth = $('.item').width(),//獲取每個節點寬度
          colLength = parseInt($ctWidth / $nodeWidth),//獲取頁面每一行數量
          itemArr = [];//初始化陣列
        for (var i = 0; i < colLength; i++) {
          itemArr[i] = 0;//便利陣列
        }
        $('.item').each(function () {
          var minValue = Math.min.apply(null, itemArr);//獲取最小值
          var minIndex = itemArr.indexOf(minValue);//獲取最小的索引值
          $(this).css({//定義位置
            top: itemArr[minIndex],//
            left: $(this).outerWidth(true) * minIndex
          });
          itemArr[minIndex] += $(this).outerHeight(true);
        });
      }
      return {
        init: init
      };
    })();
    Render.init();

瀑布流佈局的實現

相關文章