Detailed JavaScript realization Waterfall flow Absolute layout _javascript skill

Source: Internet
Author: User

Waterfall flow should be considered popular for several years. The first is a wave by the Pinterest, and then the domestic design springing up, there are many examples of waterfall flow, such as Mushroom Street, Mark's (but recently involved in yellow, as if tea), and Taobao "Wow". These are great examples, and today we'll talk about waterfall flows.
One, absolute layout:

JS Implementation principle

In fact, the main point of the waterfall is that if the picture neatly arranged in the corresponding columns, and when to start refreshing loading pictures.
And the neat arrangement of the main logic and algorithm that is, first get the container can put how many columns, and then, by calculation, storing the height of the first column, and then traversing the remaining (except the first column of the elements) of the height, respectively, into the height of the smallest column. Add one by one, and finally end the traversal.
The setting to start refreshing is simple, and the waterfall flow Refresh is only related to an event, that is, Window.onscroll. The main algorithm, that is, when the page is sliding to the lowest height to start loading the node and add, of course, the number of nodes added is not fixed.
First on the code, I am here in 3 parts to explain, one is the arrangement of pictures, one is to set the loading position. Add another response load.

1. Picture arrangement

var $ = function () {return document.querySelectorAll.apply (document, arguments); } var arrheight = []; Get a column of height var columns = function () {//calculation page can put up how many columns var containerw = $ ("#main") [0].clientwidth, PINW = $ (". Pin") [0].
  offsetwidth;
 return Math.floor (CONTAINERW/PINW); var getindex = function (arr) {//Get minimum height of index var minheight = Math.min.apply (null, arr);//Get minimum height for (var i in a
    RR) {if (arr[i] = = minheight) {return i;
 Determine the height of the first row of IMG and put them in an array based on the number of columns.
   var SetCenter = (function () {//Set width by number of columns var main = $ (' #main ') [0];//Get mask var getpadding = function () {//Set padding var col = columns ();
   Get last column var padding = main.clientwidth-col * $ ('. Pin ') [0].offsetwidth;
  return PADDING/2; var getComputedStyle = function (ele) {//compatible with IE support if (window.getcomputedstyle) {return window.getcomputedstyl
   E (ele);
   else {return ele.currentstyle; } var getpinpad = function () {//Get pin's padding value var pin = $ (". Pin")[0];
  Return parseint (getComputedStyle (PIN). Paddingleft);
  return function () {//Set width main.style.padding = ' 0 ${getpadding ()}px 0 ${getpadding ()-getpinpad ();
 }
 })(); 
   var overload = function (Ele) {var index = GetIndex (arrheight), minheight = Math.min.apply (null, arrheight),//Get minimum height
  Pins = $ ('. Pin '), style = Ele.style;
  Style.position = "absolute"; Style.top = minheight + "px";
  Sets the height of the current element style.left = pins[index].offsetleft + "px";
 Arrheight[index] + = ele.offsetheight;
   Execute functions var init = function () {var pins = $ (". Pin"), col = columns (); SetCenter (); Sets the width of the package container for (var i = 0, pin; pin = pins[i]; i++) {if (I < col) {//storage height of first row Arrheight.push (Pin.offseth
    eight);
 else {overload (PIN);//To rearrange the position of an element}}}

There are a total of 7 functions (large functions), a variable. Let's talk about ideas. First, the function executed after the page onload is init. You know, a JS program must have his entrance, the key to see how you find. Then we dive into the init function body and observe. The business logic executed within INIT is to store the height of the first row of elements and then rearrange the remaining elements. Use the columns function to get the maximum number of columns that can be dropped by the current window, and then set the center of the container (through padding settings). Next, iterate through the Pin's cell box, placing the first row of elements in the Arrheight array, and then rearrange the remaining elements. Other functions feel that there is no need to explain. Let's focus on the overload function.
2, Overload

var overload = function (Ele) {
  var index = getindex (arrheight),
   minheight = Math.min.apply (null, arrheight),//Get Minimum height
   pins = $ ('. Pin '),
   style = Ele.style;
  Style.position = "absolute";
  Style.top = minheight + "px"; Sets the height of the current element
  Style.left = pins[index].offsetleft + "px";
  Arrheight[index] + = Ele.offsetheight;
 }

There is a getindex function in the overload that gets the index of the minimum height, and then you can set the position of the incoming Ele element (absolute positioning), the highest PX value of the lowest height in the array, and the left margin position of the index element that is set for the first row. Finally update the height, OK!!! That ' s enough.
3, set the loading location

var dataint = [{' src ': ' 1.jpg '}, {' src ': ' 2.jpg '}, {' src ': ' 3.jpg '}, {' src ': ' 4.jpg '}, {' src ': ' 1.

 JPG '}, {' src ': ' 2.jpg '}, {' src ': ' 3.jpg '}, {' src ': ' 4.jpg '}]; function Isload () {//whether can be loaded var scrolltop = Document.documentElement.scrollTop | | document.body.scrollTop, WHOLEHE ight = Document.documentElement.clientHeight | | Document.body.clientHeight, point = ScrollTop + wholeheight;
  The distance at the bottom of the page from the header of var arr = $ ('. Pin ');
  var Lasthei = Arr[arr.length-1].getboundingclientrect (). Top; Return (Lasthei < point)?
 True:false;
  //Handle sliding var Dealscroll = (function () {var main = $ (' #main ') [0], flag = true; return function () {if (Isload () && flag) {for (var i = 0, data data = dataint[i++];)
     {var div = document.createelement (' div ');
     div.innerhtml = temp (DATA.SRC);
     Div.classname = "pin";
     Main.appendchild (DIV); Overload (Div);
    And the upper overload have a coupling property} flag = false; SetTimeout(function () {//) control the speed of the glide, the longer the speed of the sliding time effect of greater.
    Flag = true;
   }, 200);

 }
  }
 })(); function Temp (src) {return ' <div class= ' box ' >  </div>";

 }

In fact, the essence is in the last part, this is just as a means of loading data, of course, you can click to load (manual trigger), or other loading methods. Of course, how to set up entirely depends on you. So, follow the crowd, still rolling through the sliding load. Go on, find the entry function->dealscroll. The function performs the task of using the Isload function to determine whether the load can be judged. Let's take a look at the Isload function, which is the key point of the scrolling load.

 function Isload () {//whether can be loaded
  var scrolltop = Document.documentElement.scrollTop | | document.body.scrollTop,
   Wholeheight = Document.documentElement.clientHeight | | Document.body.clientHeight, point
   = scrolltop + wholeheight///page bottom distance from header
  var arr = $ ('. Pin ');
  var Lasthei = Arr[arr.length-1].getboundingclientrect (). Top;
  Return (Lasthei < point)? True:false;
 }

By calculation, the location of the bottom of the page from the viewport (the bottom of the tool bar) is compared to the absolute position of the last element, and loading is enabled if the sliding distance exceeds.
yeah~ that ' s over.
Back to Dealscroll
The next step is to look at the loaded part, and this part is not really saying, is to create a div node, and then put him in the end of the container, and through the overload function to handle the location of the node. In addition, at the end of the function, I set a control of the sliding speed of the trick, through the function of throttling, to prevent sometimes, requests too slow, users repeatedly send requests, resulting in waste of resources.
Then, this part can also be ended.
4. Response type
The last part is the response type, this part, also super simple, as long as you do good encapsulation, in fact, this part is to add a resize incident over the. Let's keep looking for the entry function.

 var resize = (function () {
   var flag;
   return function (FN) {
    cleartimeout (flag);
    Flag = settimeout (function () {//functions throttling to prevent users from excessively moving
     fn ();
     Console.log ("OK")
    }, (+);}
) ();

Again, the idea of function throttling is used here, and you know, as a programmer, never think users can do anything stupid. For example, when it's okay to drag the browser window to play, zoom in, zoom out, and then zoom in ... In fact, this thing I often do, because no girlfriend, write code write tired, drag the browser to play. So, given the needs of our single dog, it is necessary to use function throttling. Interested in the children's shoes, you can refer to my previous article, to learn. To illustrate, the callback function here refers to the Init function, but you need to make some changes to init. See.

 var update = function (ele) {//When resize, reset
  ele.style.position = "initial";
 }
 Execute function
 var init = functions () {
   var pins = $ (". Pin") on initialization,
    col = columns ();
   Arrheight = []; Empty height
   setcenter ()//Set width of package container for
   (var i = 0, pin; pin = pins[i]; i++) {
    if (I < col) {//Store first row height
     Arrheight.push (pin.offsetheight);
     Update (PIN);
    } else {
     overload (PIN);//To rearrange the position of an element
    }}
   }
  

You need to add update to the new first row of elements.
Then you can just move in and use it.
This is definitely the most content of the layout, about JavaScript waterfall stream another way to layout please refer to the next article "detailed JavaScript implementation waterfall streaming layout".

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.