jQuery瀑布流布局代码实例

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了瀑布流布局效果。

下面就通过代码实例介绍一下如何实现此功能。

代码实例如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<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>

回复

我来回复
  • 暂无回复内容