Home > Web Front-end > JS Tutorial > Detailed explanation of jQuery implementation of waterfall flow layout (PC and mobile)_jquery

Detailed explanation of jQuery implementation of waterfall flow layout (PC and mobile)_jquery

WBOY
Release: 2016-05-16 15:34:30
Original
1384 people have browsed it

Waterfall flow layout has become a very common way of displaying images today, whether on PC or mobile devices such as mobile phones. There are roughly three styles of layout pictures: equal heights and equal widths, equal widths and unequal heights, and equal heights and unequal widths. Next, we will take the most common form of equal widths and unequal heights as an example.

We use Baidu pictures as an example:

This is a common waterfall flow layout method on PC. Next, let’s review the elements to see how they are laid out in Baidu pictures:

As you can see, it actually contains several equal-width column containers, and the images are pushed into different containers through calculation. The display method introduced in this article is through positioning. Although the final layout display method is different, the previous algorithms are relatively similar.

Hands on

First we write several units of the following style into the body, and float the "box" to the left:

<div class="box">
 <img class="img" src="./resource/images/1.jpg" />
 <div class="desc">Description</div>
</div>
<div class="box">
 <img class="img" src="./resource/images/2.jpg" />
 <div class="desc">Description</div>
</div>
<div class="box">
 <img class="img" src="./resource/images/3.jpg" />
 <div class="desc">Description</div>
</div>
Copy after login

Get the following effect:

Next:

var boxArr = $('.box'),
  num = Math.floor(document.body.clientWidth / boxArr.eq(0).outerWidth(true)),
 columnHeightArr = [];
columnHeightArr.length = num;
boxArr.each(function(index, item) {
 if (index < num) {
 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
 });
 }
}); 

Copy after login

The above code is roughly as follows:

1. First calculate how many images (num) can be accommodated in one line in the browser. Note that outerWidth is used here. When true is passed in, the size of all box model attributes of the element including margin, padding, and border will be returned;

2. Create an array (columnHeightArr) that stores the height of each column. The length of the array is the num value;

3. Traverse all the pictures and store the picture heights in the first row into the column height array (columnHeightArr). Starting from the second row, first calculate the minimum height (minHeight) and the minimum height in all columns. column(minHeightIndex). Then position the image starting in the second row below the column with the minimum height, the effect is as follows:

You can see that although they are placed in the right place, all the pictures are placed in the same place. This is because we need to increase the height of the column after placing a picture:

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

boxArr.each(function(index, item) {
  if (index < num) {
    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);
  }
});

Copy after login

The result is correct:

Note: The above code needs to be run in the window.onload method, because only when all the image resources in the page are loaded, the height of each image will be efficient.

Therefore, there will be some very serious problems. When the network is not good, the picture will not be fully loaded, and the picture will be incompletely displayed and the height will be missing. This is obvious on the mobile side. And when we load more, it becomes more difficult to judge whether the newly added images have been loaded.

In actual production, it is not possible to write images in HTML from the beginning, so we usually do it in the following way:

First of all, when we get the image address, we also need to get the width and height of the image. This is not difficult for the server backend. You can ask the backend brothers to spell the width and height data of the image into JSON and pass it to you. ;

* Next, I will introduce a little trick , which is very practical. It can ensure that no matter how the size of an element changes, the proportion will always remain consistent . This technique works especially well on mobile because elements often use percentages to make them responsive.

If there is an image on a mobile phone page, its width should be half of the screen and its aspect ratio should be 2:1. The ratio needs to remain unchanged on mobile phones with any resolution. How to do it? Set the following attributes to the element:

.box {
 width: 50%;
 height: 0;
 padding-bottom: 100%;
}
Copy after login

不设置高度,而是用padding“挤”出元素高度,而padding的百分比值都是基于父级容器的宽度。padding需要挤多少呢?就是宽度乘以高宽比(width和padding值均为百分比值),这就是我们为什么需要获得图片尺寸的原因。

效果:

可以看到在chrome手机模拟器中ipone4和肾6Plus的显示效果是完全一样的。在手机页面中宽是固定的,而高会随着页面内容的多少而变化,这个技巧利用元素padding百分比的值其实是基于其父级容器的宽,将高的值巧妙的转化成与宽相关。

说到现在可能有人终于忍不住要问了,讲了这么多和瀑布流有什么关系!简单就是一句话,我们要抛弃 img 标签,而采用背景图的方式。为了使用背景图,就得保持元素的比例永远与图片保持一致。

通过这种方式,可以不用判断图片都加载完毕,直接产生一些与图片同比例的div,再为其设置背景图,如下:

这里比如最外层的box宽度为220px,里面的img元素宽度就可以为100%,高度就可以通过padding挤出了。

懒加载

使用背景图的方式还有好处那就是可以比较方便的实现懒加载。那什么是懒加载呢?就是当元素在我们的视野中时才展示图片,滚动时屏幕下方的图片并不展示,这可以很好的增加加载速度提升体验。

首先我们给最外层的box增加一个box-item类名(之后有用),将图片url并不设置给backgroundImage属性,而是赋给一个自定义属性:data-src

<div class="box box-item">
 <div class="img" data-src="./resource/images/1.jpg"></div>
 <div class="desc">Description</div>
</div>
Copy after login

接下来我们编写懒加载函数:

function lazyLoad() {
  var boxArr = $('.box-item');
  
  boxArr.each(function(index, item) {
    var viewTop = $(item).offset().top - $(window).scrollTop(),
 imgObj = $(item).find('.img');

 if ((viewTop < $(window).height()) && (($(item).offset().top + $(item).outerHeight(true)) > $(window).scrollTop())) {
   imgObj.css('backgroundImage','url('+imgObj.attr("data-src")+')').removeClass('data-src');
   $(item).removeClass('box-item');
 }
 })
}

Copy after login

首先我们获取所有拥有 .box-item 类名的元素,遍历。viewTop 为图片相对于浏览器窗口的相对高度,类似于position:fixed感觉。

通过条件进行判断,只有当该图片在浏览器窗口内(之上或之下都不行)时,将需要设置背景图元素的 data-src 值展示出来,并删除该属性。

之后将最外层元素的 box-item 删除,因为已经展示出来的图片不需要再进行这些判断,删除了该类名下一次滚动时就不会获取到已经展示过的元素,需要遍历的次数就会越来越少,这样能起到一个优化的作用。

该函数需要在你的元素已经append进页面时调用,以及在滚动时调用:

lazyLoad();
$(window).scroll(lazyLoad);

滚动加载

说完了懒加载,再说说滚动加载。所谓滚动加载就是当页面滚动到底部附近时加载新的图片。我这里选择的是滚动到高度最小的列底部时加载新的数据,你也可以根据自己的喜好来做判断。

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

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

Copy after login

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

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

说完了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);
  }
});
Copy after login

不同的是为了适应不同屏幕的手机,最外层的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();

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

 lazyLoad();

 function arrangement() {
 boxArr.each(function(index, item) {
 if (index < num) {
 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);
 }
 });
 }

 function lazyLoad() {
 var boxArr = $('.box-item');
 boxArr.each(function(index, item) {
 var viewTop = $(item).offset().top - $(window).scrollTop(),
 imgObj = $(item).find('.img');
 if ((viewTop < $(window).height()) && ($(item).offset().top + $(item).outerHeight(true) > $(window).scrollTop())) {
// console.log($(item).attr('data-src'));
 imgObj.css('backgroundImage','url('+imgObj.attr("data-src")+')').removeClass('data-src');
 $(item).removeClass('box-item');
 }
 })
 }

 function cRate(obj) {
 return obj.height / obj.width;
 }

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

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

以上就是为大家分享的关于jQuery瀑布流布局,内容很丰富,需要大家一点点的理解消化,真正的做到学以致用,希望能够帮助到大家。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template