css:css
<style>
*{margin: 0;padding: 0;}
img{max-width: 100%;}
.container{max-width: 1200px;margin: 0 auto;}
.waterfall{position: relative;}
.waterfall .item{position: absolute;}
</style>
html:
<div class="container">
<div class="waterfall">
<div class="item">
<img src="img/block8.jpeg" alt="">
</div>
<div class="item">
<img src="img/product_img.jpg" alt="">
</div>
<div class="item">
<img src="img/block6_1.jpg" alt="">
</div>
<div class="item">
<img src="img/banner.jpg" alt="">
</div>
<div class="item">
<img src="img/block8.jpeg" alt="">
</div>
<div class="item">
<img src="img/product_img.jpg" alt="">
</div>
<div class="item">
<img src="img/block6_1.jpg" alt="">
</div>
<div class="item">
<img src="img/banner.jpg" alt="">
</div>
</div>
</div>
js:
<script> $.fn.waterfall = function(){ let _this = $(this), _child = _this.children(), col = 3,/*列數*/ offset = 10,/*間隔*/ heightArr = [];/*存放每一列的高度*/ /*設置寬度*/ width = (_this.innerWidth()-offset*(col-1))/col; _child.width(width); /*存放最前面3個元素的高度*/ for(let i = 0;i<col;i++){ heightArr.push(_child.eq(i).innerHeight()); } var minH = 0;/*最低高度*/ for(let i=0;i<_child.length;i++){ let minIndex = 0; if(i<col){ minH = 0 ; minIndex = i; }else{ minH = heightArr[0]; for(let j = 0;j<heightArr.length;j++){ if(heightArr[j]<=minH){ minH = heightArr[j]; minIndex = j; } } minH+=offset; heightArr[minIndex] = minH+_child.eq(i).innerHeight(); } _child.eq(i).css({ top:minH, left:width*minIndex+offset*minIndex }); } /*設置父容器高度*/ _this.height(minH+_this.children(":last-child").innerHeight()); }; window.onload = function(){ $('.waterfall').waterfall(); }</script>