1.什么是瀑布流?
就是多行等宽元素排列,后面的元素依次添加到其后,宽度相同高不同,根据图片原比例缩放直至宽度达到我们的要求,依次按照规则放入指定位置。
2.实现原理:
图片定位:position:absolute;
left:最小索引*图片宽度;
top:最小图片的高度;
将第一行每个图片高度存放一个数组,heightArr = [100,50,150,100];当放入下一个图片时,判断数组中最小的高度,再通过索引进行定位;然后根据这个方法,遍历所有的元素;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>瀑布流布局</title> <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script> <style> .main { position: relative; } .box { display:inline-block; 200px; vertical-align: top; padding: 8px; } img{ 100%; } </style> </head> <body> <div class="main"> <div class="box"><img src="imgs/001.png" alt=""></div> <div class="box"><img src="imgs/002.png" alt=""></div> <div class="box"><img src="imgs/003.png" alt=""></div> <div class="box"><img src="imgs/004.png" alt=""></div> <div class="box"><img src="imgs/005.png" alt=""></div> <div class="box"><img src="imgs/006.png" alt=""></div> <div class="box"><img src="imgs/007.png" alt=""></div> <div class="box"><img src="imgs/008.png" alt=""></div> <div class="box"><img src="imgs/009.png" alt=""></div> <div class="box"><img src="imgs/010.png" alt=""></div> </div> </body> </html> <script type="text/javascript"> $(function(){ walterFall() }); function walterFall(){ var box = $('.box'); var boxWidth = box.outerWidth(); var screenWidth = $(window).width(); // 求出列数 var cols = parseInt(screenWidth/boxWidth); // 创建数组 var heightArr = []; // 对图片进行遍历循环,第一行不需要定位,取高度值,其他行数进行定位处理 $.each(box,function(index,item){ var boxHeight = $(item).outerHeight(); // 先判断是否为第一排 if( index < cols ){ console.log(index); heightArr[index] = boxHeight; }else{ // 数组中最小的值 var minBoxHeight = Math.min(...heightArr);//ES6扩展运算符,序列化处理 // 最小索引 $.inArray();查找对应数组中指定的值,返回索引(未找到返回-1) var minBoxIndex = $.inArray(minBoxHeight,heightArr); console.log(minBoxIndex); $(item).css({ position:'absolute', left: minBoxIndex * boxWidth +'px', top: minBoxHeight + 'px' }); // 高度追加 heightArr[minBoxIndex] += boxHeight; } }) }; // 窗口大小改变 $(window).resize(function () { walterFall(); }); </script>
3. 实现效果: