Home Web Front-end JS Tutorial Introduction to using Jquery waterfall flow plug-in_jquery

Introduction to using Jquery waterfall flow plug-in_jquery

May 16, 2016 pm 05:48 PM
Waterfalls flow

A brief analysis of waterfall flow layout

A brief discussion of the problems and solutions encountered by individuals in the implementation of waterfall flow web pages

Toss: waterfall flow layout (implemented based on multi-column list fluid layout)

javascript waterfall flow, Brief analysis and suggestions of major waterfall flows

Because I use jquery a lot, I came up with the idea of ​​making waterfall flow into a plug-in. Let’s borrow the beautiful pictures from Xunlei UED.

Take a look firstDemo

Publish the code

Copy the code The code is as follows:

;(function($){
var
//参数
setting={
column_width:204,//列宽
column_className:'waterfall_column',//列的类名
column_space:10,//列间距
cell_selector:'.cell',//要排列的砖块的选择器,限定在瀑布流的容器内
img_selector:'img',//要加载的图片的选择器
auto_imgHeight:true,//是否需要自动计算图片的高度
fadein:true,//是否渐显载入
fadein_speed:600,//渐显速率,单位毫秒
insert_type:1, //砖块插入方式,1为插入最短那列,2为按序轮流插入
getResource:function(index){ } //获取动态资源函数,必须返回一个砖块元素集合,传入参数为加载的次数
},
//
waterfall=$.waterfall={},
$container=null;//容器
waterfall.load_index=0, //加载次数
$.fn.extend({
waterfall:function(opt){
opt=opt||{};
setting=$.extend(setting,opt);
$container=waterfall.$container=$(this);
waterfall.$columns=creatColumn();
render($(this).find(setting.cell_selector).detach(),false); //重排已存在元素时强制不渐显
waterfall._scrollTimer2=null;
$(window).bind('scroll',function(){
clearTimeout(waterfall._scrollTimer2);
waterfall._scrollTimer2=setTimeout(onScroll,300);
});
waterfall._scrollTimer3=null;
$(window).bind('resize',function(){
clearTimeout(waterfall._scrollTimer3);
waterfall._scrollTimer3=setTimeout(onResize,300);
});
}
});
function creatColumn(){//创建列
waterfall.column_num=calculateColumns();//列数
//循环创建列
var html='';
for(var i=0;ihtml+='
';
}
$container.prepend(html);//Insert column
return $('.' setting.column_className,$container);//Column collection
}
function calculateColumns(){//Calculate the required number of columns
var num=Math.floor(($container.innerWidth())/(setting.column_width setting.column_space));
if(num<1) { num=1; } // Ensure at least one column
return num;
}
function render(elements,fadein){//Render elements
if(!$(elements).length) return;//No elements
var $columns = waterfall.$columns;
$(elements).each(function(i){
if(!setting.auto_imgHeight||setting.insert_type==2 ){//If the image height is given, or inserted in order, the height of the column can be calculated without waiting for the image to be loaded
if(setting.insert_type==1){
insert($( elements).eq(i),setting.fadein&&fadein);//Insert element
}else if(setting.insert_type==2){
insert2($(elements).eq(i),i,setting .fadein&&fadein);//Insert element
}
return true;//continue
}
if($(this)[0].nodeName.toLowerCase()=='img'|| $(this).find(setting.img_selector).length>0){//Itself is an image or contains an image
var image=new Image;
var src=$(this)[0].nodeName. toLowerCase()=='img'?$(this).attr('src'):$(this).find(setting.img_selector).attr('src');
image.onload=function() {//The size can be automatically calculated after the image is loaded
image.onreadystatechange=null;
if(setting.insert_type==1){
insert($(elements).eq(i),setting. fadein&&fadein);//Insert element
}else if(setting.insert_type==2){
insert2($(elements).eq(i),i,setting.fadein&&fadein);//Insert element
}
image=null;
}
image.onreadystatechange=function(){//Handle the caching problem of browsers such as IE: the onload event will no longer be triggered after the image is cached
if(image .readyState == "complete"){
image.onload=null;
if(setting.insert_type==1){
insert($(elements).eq(i),setting.fadein&&fadein) ;//Insert element
}else if(setting.insert_type==2){
insert2($(elements).eq(i),i,setting.fadein&&fadein);//Insert element
}
image=null;
}
}
image.src=src;
}else{//No need to consider image loading
if(setting.insert_type==1){
insert($(elements).eq(i),setting.fadein&&fadein);//Insert element
}else if(setting.insert_type==2){
insert2($(elements).eq( i),i,setting.fadein&&fadein);//Insert element
}
}
});
}
function public_render(elem){//Asynchronous data rendering interface function
render(elem,true);
}
function insert($element,fadein){//Insert the element into the shortest column
if(fadein){//Fade in
$element.css ('opacity',0).appendTo(waterfall.$columns.eq(calculateLowest())).fadeTo(setting.fadein_speed,1);
}else{//Do not fade in
$element.appendTo (waterfall.$columns.eq(calculateLowest()));
}
}
function insert2($element,i,fadein){//Insert elements in sequence
if(fadein) {//Fade
$element.css('opacity',0).appendTo(waterfall.$columns.eq(i%waterfall.column_num)).fadeTo(setting.fadein_speed,1);
} else{//Do not fade in
$element.appendTo(waterfall.$columns.eq(i%waterfall.column_num));
}
}
function calculateLowest(){//Calculate the shortest The index of that column
var min=waterfall.$columns.eq(0).outerHeight(),min_key=0;
waterfall.$columns.each(function(i){
if($ (this).outerHeight()min=$(this).outerHeight();
min_key=i;
}
});
return min_key;
}
function getElements(){//Get resources
$.waterfall.load_index;
return setting.getResource($.waterfall.load_index,public_render);
}
waterfall. _scrollTimer=null;//Delayed scrolling loading timer
function onScroll(){//Scrolling loading
clearTimeout(waterfall._scrollTimer);
waterfall._scrollTimer=setTimeout(function(){
var $lowest_column=waterfall.$columns.eq(calculateLowest());//The shortest column
var bottom=$lowest_column.offset().top $lowest_column.outerHeight();//The distance between the bottom of the shortest column and the top of the browser window The distance
var scrollTop=document.documentElement.scrollTop||document.body.scrollTop||0;//Scroll bar distance
var windowHeight=document.documentElement.clientHeight||document.body.clientHeight||0 ;//Window height
if(scrollTop>=bottom-windowHeight){
render(getElements(),true);
}
},100);
}
function onResize(){//Rearrange when the window is zoomed
if(calculateColumns()==waterfall.column_num) return; //The number of columns has not changed, no need to rearrange
var $cells=waterfall.$container. find(setting.cell_selector);
waterfall.$columns.remove();
waterfall.$columns=creatColumn();
render($cells,false); //When rearranging existing elements Force not to fade out
}
})(jQuery);

It seems that the format of pasting the code is a bit messy, so I won’t care about it for now. If you can't see the above code clearly, you can view the source file directly on the demo page.
How to use the plug-in:
Copy the code The code is as follows:
$(selector).waterfall(opt); //where selector is the selector of the waterfall flow container, opt is the configuration parameter object

The required html structure: the html structure can be an empty container element , such as
, the brick elements inside are loaded dynamically. Of course, you can also put some bricks in advance, such as

in the demo page. Copy the code . The code is as follows:


00

01


< ;div class="cell">

02


< ;img src="P_003.jpg" />

03


04


05

06


< ;div class="cell">

07


< ;img src="P_008.jpg" />

08


09


10

11


< ;div class="cell">

12


< ;img src="P_013.jpg" />

13


14


15

16


< ;div class="cell">

17


< ;img src="P_018.jpg" />

18


19



The following is a detailed description of the functions and default values ​​of each attribute of the configuration parameter object opt.

column_width:204 //Waterfall flow is composed of columns. This parameter specifies the width of each column. This parameter will directly affect the number of columns in the waterfall flow

column_className:'waterfall_column' //The class name of the column, easy to customize the style

column_space:10 //The spacing between columns

cell_selector:'.cell' //The selector of the bricks to be arranged is limited to the container of the waterfall flow, that is, the plug-in obtains the brick elements through this selector, and is Find elements matching this selector within the waterfall container.

img_selector:'img' //Selector for the image to be loaded. If the theme content of the brick elements to be loaded by your waterfall flow is images of varying sizes, then this parameter is the selector of these images, and the plug-in needs to obtain these images for calculation.

auto_imgHeight:true //Do you need to automatically calculate the height of the image? If the size of the image is fixed, set this parameter to false

fadein:true // Whether to fade in and load

fadein_speed:600 //Fade in speed in milliseconds

insert_type:1 //Brick insertion method, 1 means inserting the shortest column, 2 means inserting in sequence

getResource:function(index,render){ } //Get the dynamic resource function, which must return a collection of brick elements. The first parameter index passed in is the number of times it has been loaded. The second parameter is the number of times it has been loaded. The first parameter is the rendering function, which can accept a collection of brick elements as a parameter. If you use ajax to load data, you must manually call the function to render after getting the data. This function is automatically triggered every time the bottom of the waterfall is reached to load more resources.

Comment time:

The content loaded by waterfall flow is generally pictures with the same width and different heights. If the height of the picture can be known in advance, it will be much simpler. But if not, you must wait until the picture is loaded before you can calculate the height of the picture. This This is the most annoying part of the waterfall flow. It is precisely because of this that if the height of the pictures is unknown, the order of insertion may be a little confusing, and the refresh order is different every time, because the order in which each picture is loaded is not the same. It's not fixed, maybe this time is faster, next time that is faster. Therefore, if the height of the image is not known in advance, the height of the entire brick will also be unknown. The height of the brick must be calculated after the image in the brick is loaded. If this is the case but you want to ensure the insertion order of bricks, it is recommended to insert bricks in sequence, that is, set the insert_type parameter to 2. Because it is a plug-in, ease of use must be considered, but the easier it is to use, the more complex the plug-in will be inside, and the number of loopholes and bugs will increase, so I will continue to improve this plug-in.

This plug-in supports IE6, chrome, firefox, opera, safari and other mainstream browsers.

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles