瀑布流的实现

匿名 (未验证) 提交于 2019-12-02 21:53:52

现在很多网站都会使用瀑布流的一个效果,什么是瀑布流呢,用在哪些地方呢?

大概就是这样的一个效果,一般用于无法保证图片大小的网站。

先看下布局+css

 1     .cont{margin: 0 auto;position: relative;}  2         .box{float: left;padding: 6px}  3         .imgbox{border: solid 1px black;border-radius: 6px;padding: 6px}  4         .imgbox img{width:200px;display: block;}  5   6   7     <div class="cont">  8         <div class="box">  9             <div class="imgbox"> 10                 <img src="images/4.jpg" alt=""> 11             </div> 12         </div> 13     </div>

  瀑布流:第一行正常浮动,从第二行开始,每个元素都定位到上一行的最小高度的元素下
思路就是这样,这里的难点在于找到第一行和最小高度;将思路列出就会很清晰的知道自己要做些什么;所以还是比较推荐用面向对象去写,后续的使用会更多。可以用这些小案例来练手,增加熟练度。
 1     function Waterfall(){  2             // 1.获取元素  3             this.ocont = document.querySelector(".cont");  4             this.abox = document.querySelectorAll(".box");  5   6             // 将来准备存放第一行元素所有高度的数组  7             this.heightArr = [];  8   9             // 2.布局 10             this.init() 11         } 12         Waterfall.prototype.init = function(){ 13             // 布局 14             this.num = Math.floor(document.documentElement.clientWidth / this.abox[0].offsetWidth) 15  16             this.ocont.style.width = this.num * this.abox[0].offsetWidth + "px"; 17             // 3.区分第一行 18             this.firstLine(); 19             // 和后面的行 20             this.otherLine(); 21         } 22         Waterfall.prototype.firstLine = function(){ 23             // 4.在第一行,找到第一行所有的高度 24             for(var i=0;i<this.num;i++){ 25                 this.heightArr.push(this.abox[i].offsetHeight) 26             } 27         } 28         Waterfall.prototype.otherLine = function(){ 29             // 5.在后面的行,找到最小高度 30             for(var i=this.num;i<this.abox.length;i++){ 31                 var min = getMin(this.heightArr); 32                 var minIndex = this.heightArr.indexOf(min); 33                 // 设置定位,left,top 34                 this.abox[i].style.position = "absolute"; 35                 this.abox[i].style.top = min + "px"; 36                 this.abox[i].style.left = minIndex * this.abox[0].offsetWidth + "px"; 37                 // 6.修改之前的最小高度 38                 this.heightArr[minIndex] += this.abox[i].offsetHeight; 39             } 40         } 41  42         function getMin(arr){ 43             // 注意数组的深浅拷贝:深拷贝 44             var myarr = []; 45             arr.forEach(val => { 46                 myarr.push(val); 47             }); 48             return myarr.sort((a,b)=>a-b)[0]; 49         }

还有一个无限加载的小功能,我简单说下思路吧,可以自己写写看!

  W1.准备数据--->自己模拟数组,假装后台给的
思路就是这样,有疑问可以找我哈!加油冲吧!
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!