jQuery瀑布流佈局程式碼例項

antzone發表於2017-04-12

本章節分享一段程式碼例項,它實現了瀑布流佈局效果。

下面就通過程式碼例項介紹一下如何實現此功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style>
* {
  padding: 0;
  margin: 0;
}
.main {
  position: relative;
}
.box {
  float: left;
  width: 150px;
  border: 1px solid #ccc;
  box-shadow: 0 0 6px #ccc;
  border-radius: 5px;
  background-color: #eef;
  margin: 15px;
}
</style>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script>
function createRandomNumber() {
  var num = Math.floor((Math.random() + 2) * 100);
  return num;
}
function waterfall() {
  var box = $(".box");
  var boxWidth = box.eq(0).outerWidth(true);
  var num = Math.floor($(window).width() / boxWidth);
  $(".main").width(boxWidth * num).css({
    "margin": "0 auto"
  });
  var arrHeight = [];
  box.each(function (index, value) {
    if (index < num) {
      arrHeight[index] = box.eq(index).outerHeight(true);
    }
    else {
      var minHeight = Math.min.apply(null, arrHeight);
      var minHeightIndex = $.inArray(minHeight, arrHeight);
      $(value).css({
        "position": "absolute",
        "top": minHeight,
        "left": box.eq(minHeightIndex).position().left
      });
      arrHeight[minHeightIndex] += box.eq(index).height() + 15;
    }
  });
}
 
function checkscroll() {
  var box = $(".box");
  var lastBoxHeight = box.last().get(0).offsetTop + box.last().outerHeight(true); 
  var scrollTop = $(window).scrollTop();
  var documentHeight = $(document).height();
  return (lastBoxHeight < scrollTop + documentHeight) ? true : false;
}
 
window.onload = function () {
  $(".box").each(function (index, value) {
    $(".box").eq(index).height(createRandomNumber());
  });
  waterfall();
  window.onscroll = function () {
    if (checkscroll()) {
      for (var i = 0; i < 5; i++) {
        var box = $("<div class='box'></div>").appendTo(".main");
        box.height(createRandomNumber());
      }
      waterfall();
    }
  }
}
</script>
</head>
<body>
  <div class="main">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</body>
</html>

相關文章