jQuery实现瀑布流布局详解(PC和移动端)

2020-05-29 06:57:04易采站长站整理


function scrollLoad() {
  var viewHeight = $(window).scrollTop() + $(window).height(),
minHeight = Math.min.apply(null, columnHeightArr);

  if (viewHeight >= minHeight) {
  //loadMore...
  }
}

滚动加载也是在window的滚动事件中进行监听,可以与懒加载一起进行:


$(window).scroll(function() {
scrollLoad();
lazyLoad();
});

说完了PC端,我们来说下手机端。其实原理是一样的,只是从多列变成固定的两列了。


var boxArr = $('.box'),
columnHeightArr = [];
columnHeightArr.length = 2;

boxArr.each(function(index, item) {
  if (index < 2) {
    columnHeightArr[index] = $(item).outerHeight(true);
  } else {
    var minHeight = Math.min.apply(null, columnHeightArr),
minHeightIndex = $.inArray(minHeight, columnHeightArr);

    $(item).css({
  position: 'absolute',
  top: minHeight,
  left: boxArr.eq(minHeightIndex).position().left
});

    columnHeightArr[minHeightIndex] += $(item).outerHeight(true);
  }
});

不同的是为了适应不同屏幕的手机,最外层的box容器宽度和边距要设置成百分比的形式。

 最后有一点要注意,因为我们没有像百度一样用一个个列盒子去装,而是用定位的方式。导致的问题是图片元素的父级没法自适应高度,如果你有相关的需求我们可以计算出所有列中最长的长度,并将这个值赋值给父容器的min-height属性:

$(‘body’).css(‘minHeight’,Math.max.apply(null, columnHeightArr)); 

整理下完整的代码,瀑布流的全套服务就到这了


var dataArr = [
{picUrl:'./resource/images/1.jpg',width:522,height:783},
{picUrl:'./resource/images/2.jpg',width:550,height:786},
{picUrl:'./resource/images/3.jpg',width:535,height:800},
{picUrl:'./resource/images/4.jpg',width:578,height:504},
{picUrl:'./resource/images/5.jpg',width:1440,height:900}
];

$.each(dataArr, function(index, item) {
$("body").append('<div class="box box-item">' +
'<div class="img" style="height:0;padding-bottom:'+cRate(item) * 100 + "%"+'" data-src="'+item.picUrl+'"></div>' +
'<div class="desc">Description</div>' +
'</div>');
});

var boxArr = $('.box'),
num = Math.floor(document.body.clientWidth / boxArr.eq(0).outerWidth(true)),
columnHeightArr = [];
columnHeightArr.length = num;

arrangement();