Principle:
Gets the width of a picture (the width of all pictures is certain).
Calculates the number of columns (page width/image width) of a row of pictures in the browser.
New an array that holds the height of the superimposed image.
For the number of pictures in the For loop, which is less than the number of columns, add directly to the page and push the height of the image into the array.
is larger than the number of columns, the height of the picture is stacked upwards.
HTML section:
<body> <div id= "main" > <div class= "box" > <div class= "pic" > </div> </div> <div class= "box" > <div class= "pic" > </div> </div> <div class= "box" > <div class= "pic" > </di V> </div>/* Just a few more pictures with the same */</div> </body>
CSS section:
*{margin:0; padding:0;} #main {position:relative;}. box{padding:15px 0 0 15px; Float:left; }.pic{padding:10px; border:1px solid #ccc; border-radius:5px; box-shadow:0px 0px 5px #ccc;}. Pic img{width:165px; Height:auto;}
The most central part of the--JS:
Window.onload =function () { waterfall (' Main ', ' box ');} Function waterfall (Parent,box) { var oparent = document.getElementById (parent); var oboxs=getbyclass (oparent,box);// Gets all the child elements of the box under the parent element var oboxw=oboxs[0].offsetwidth; // Number of columns var clos=math.floor (DOCUMENT.DOCUMENTELEMENT.CLIENTWIDTH/OBOXW); //set the width of main oparent.style.csstext= ' width: ' +oboxw*clos+ ' px;margin:0 Auto '; var arrh=new array (); for (var i=0;i< oboxs.length;i++) { if (I<clos) { arrh.push (oboxs[i].offsetheight); }else{ //get the smallest picture of the height var minh=math.min.apply (Null,arrH); //get the index of the height of the smallest picture var index=getindexminh (ArrH,minH); oboxs[i].style.position= ' Absolute '; oBoxs[i].style.top=arrH[index]; oBoxs[i].style.left=oBoxs[index].offsetLeft; arrH[index]=arrH[index]+oBoxs[i].offsetHeight; } } console.log (ArrH);} Function getbyclass (Parent,box) { var boxs=new array ();//Used to access box elements tags= parent.getelEmentsbytagname (' * ');//Gets all the elements under the parent element for (var i=0;i<tags.length;i++) { if (Tags[i].classname==box) { boxs.push (Tags[i]); } } return boxs;} Function getindexminh (arr,val) { for (Var i in arr) { if (Arr[i]==val) { return i; } }}
JS to achieve waterfall flow