<!DOCTYPE html>
<html>
<head>
<title>瀑布流</title>
<meta charset="utf-8">
</head>
<style type="text/css">
ul,li{list-style: none; }
*{margin:0; padding:0; }
.img-wrap{width:800px; background: #eee;position: relative; }
.img-wrap li{width:200px; margin:10px 10px;float: left;background: #ccc;text-align: center; }
.img-wrap img{width:100%;}
</style>
<body>
<ul class="img-wrap">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(window).on('load',function(){
waterFall();
})
function waterFall(){
let imgWrapWidth = $('.img-wrap').outerWidth(true);
let imgWidth = $('.img-wrap li').outerWidth(true);
let cols = parseInt( imgWrapWidth / imgWidth); //一列可以有多少个
let allImg = $('.img-wrap li');
let heightArr = [];
$.each(allImg,function(index,item){
let itemHeight = parseInt(Math.random() * 500);
$(item).css({height:itemHeight,lineHeight:itemHeight + 'px'})
$(item).text(`${imgWidth} * ${itemHeight}`)
if(index < cols){
heightArr.push(itemHeight+20);
}else{
let minH = Math.min(...heightArr);
let minHeightIndex = heightArr.indexOf(minH);
$(item).css({
position:'absolute',
left:minHeightIndex * imgWidth + 'px',
top:minH + 'px'
})
heightArr[minHeightIndex] += itemHeight+20;
}
})
}
</script>