jq实现瀑布流

发布时间:2020-08-13 22:00:19发布者:Mr.Zhang阅读(296)

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>




本文转自博客园,原文地址:https://www.cnblogs.com/myyt/p/13404010.html

自己做的一款记账小程序,请多多支持