一、waterfall.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>瀑布流</title>
<script src="js/jQuery_3.5.0.js"></script>
<script src="js/jQuery_waterfall.js"></script>
<style>
*{
margin: 0;
padding: 0;
}
#main{
position: relative;
}
.pin{
padding: 15px 0 0 15px;
float: left;
}
.box{
padding: 5px;
border: 1px solid #ccc;
box-shadow: 0 0 6px #cccccc;
border-radius: 5px;
}
.box img{
width: 236px;
height: auto;
}
</style>
</head>
<body>
<div id="main">
<div class="pin">
<div class="box">
<img src="img/xuelian1.jpg">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian2.jpg">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian3.jpg">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian4.jpg">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian5.jpg">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian6.jpg">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian7.png">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian1.jpg">
</div>
</div>
<div class="pin">
<div class="box">
<img src="img/xuelian2.jpg">
</div>
</div>
</div>
</body>
</html>
二、jQuery_waterfall.js
$(function () {
$(window).on("load" , function () {//图片加载完成再显示
imageLocation();
var dataImg = {"data":[{"src":"xuelian1.jpg"} , {"src":"xuelian2.jpg"}]};
$(window).scroll(function () {
if (getSideHeight()){
$.each(dataImg.data , function (index , value) {
var pin = $("<div>").addClass("pin").appendTo("#main");
var box = $("<div>").addClass("box").appendTo(pin);
var img = $("<img>").attr("src" , "img/"+$(value).attr("src"));
img.appendTo(box);
})
imageLocation();
}
})
})
})
function getSideHeight() {
var box = $(".pin");
//获取最后一张图片距离顶端的高度 - 它自身的一半
var lastImageHeight = (box.last().get(0)).offsetTop - Math.floor(box.last().height()/2);
var documentHeight = $(document).height();//获取当前窗口的一个高度
var scrollHeigh = $(window).scrollTop();//获取滚动的距离
console.log(" lastImageHeight: " + lastImageHeight + " documentHeight: " + documentHeight + " scorllHeight: "+ scrollHeigh);
return (lastImageHeight < documentHeight + scrollHeigh)?true:false;
}
function imageLocation() {
var box = $(".pin");//返回一个数组
var boxWidth = box.eq(0).width();//每张图片的宽度
var num = Math.floor($(window).width()/boxWidth);//一行能放的图片的数量
var numArr = [];
box.each(function (index , value) {
var boxHeight = box.eq(index).height();//获取每张图片的高度
if (index < num){ //第一行
numArr[index] = boxHeight;
}else {//第二行
var minboxHeight = Math.min.apply(numArr , numArr);
var minIndex = $.inArray(minboxHeight , numArr);//最小高度图片的索引值
$(value).css({
position:"absolute",
top:minboxHeight,
left:box.eq(minIndex).position().left
});
numArr[minIndex] +=box.eq(index).height();
}
})
}