<html>
<head>
<meta charset="utf-8">
<title>瀑布流</title>
<style type="text/css">
#main {
position: relative;
}
.box {
padding: 5px;
float: left;
}
.pic {
height: auto;
padding: 5px;
border: 1px solid gray;
border-radius: 5px;
}
.pic img {
width: 200px;
}
</style>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<script>
window.onload = function () {
waterfall();
}
window.onscroll = function () {
var lastBox = $("#main>div").last();
var lastH = lastBox.offset().top + Math.floor(lastBox.outerHeight());
var soc = $(window).scrollTop();
var docHeight = $(window).height();
if (lastH - docHeight - soc < 50) {
console.log("加载" + (lastH - docHeight - soc));
var jsonData = {
"data": [
{ "src": "images/02.jpg" }, { "src": "images/03.jpg" },
{ "src": "images/01.jpg" }, { "src": "images/02.jpg" },
{ "src": "images/03.jpg" }, { "src": "images/04.jpg" },
{ "src": "images/04.jpg" }, { "src": "images/02.jpg" },
{ "src": "images/05.jpg" }, { "src": "images/04.jpg" },
]
};
$(jsonData.data).each(function (i, item) {
var oBox = $("<div>").addClass("box").appendTo($("#main"));
var pic = $("<div>").addClass("pic").appendTo(oBox);
$("<img>").attr("src", item.src).appendTo(pic);
});
waterfall();
}
}
function waterfall() {
var $box = $("#main>div");
var w = $box.eq(0).outerWidth();
var cols = Math.floor($(window).width() / w);
$("#main").width(w * cols).css("margin", "0 auto");
var hArr = [];
$box.each(function (i, item) {
var h = $box.eq(i).outerHeight();
if (i < cols) {
hArr[i] = h;
} else {
var minH = Math.min.apply(null, hArr);
var minInx = $.inArray(minH, hArr);
// console.log(minH + '--' + minInx);
$(item).css({
"position": "absolute",
"top": minH + "px",
"left": minInx * w + "px"
});
hArr[minInx] += $box.eq(i).outerHeight();
}
});
}
</script>
</head>
<body>
<div id="main">
<div class="box">
<div class="pic">
<img src="images/01.jpg" />
</div>
</div>
</div>
</body>
</html>