瀑布流 jq
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> *{margin: 0;padding: 0;} img{max-width: 100%;} .container{max-width: 1200px;margin: 0 auto;} .waterfall{position: relative;} .waterfall .item{position: absolute;} </style> </head> <body> <div class="container"> <div class="waterfall"> <div class="item"> <img src="img/1.jpg" alt=""> </div> <div class="item"> <img src="img/2.jpg" alt=""> </div> <div class="item"> <img src="img/1.jpg" alt=""> </div> <div class="item"> <img src="img/2.jpg" alt=""> </div> <div class="item"> <img src="img/1.jpg" alt=""> </div> <div class="item"> <img src="img/2.jpg" alt=""> </div> <div class="item"> <img src="img/2.jpg" alt=""> </div> <div class="item"> <img src="img/1.jpg" alt=""> </div> </div> </div> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script> <script> $.fn.waterfall = function(){ let _this = $(this), _child = _this.children(), col = 3,/*列数*/ offset = 10,/*间隔*/ heightArr = [];/*存放每一列的高度*/ /*设置宽度*/ width = (_this.innerWidth()-offset*(col-1))/col; _child.width(width); /*存放最前面3个元素的高度*/ for(let i = 0;i<col;i++){ heightArr.push(_child.eq(i).innerHeight()); } var minH = 0;/*最低高度*/ for(let i=0;i<_child.length;i++){ let minIndex = 0; if(i<col){ minH = 0 ; minIndex = i; }else{ minH = heightArr[0]; for(let j = 0;j<heightArr.length;j++){ if(heightArr[j]<=minH){ minH = heightArr[j]; minIndex = j; } } minH+=offset; heightArr[minIndex] = minH+_child.eq(i).innerHeight(); } _child.eq(i).css({ top:minH, left:width*minIndex+offset*minIndex }); } /*设置父容器高度*/ _this.height(minH+_this.children(":last-child").innerHeight()); }; window.onload = function(){ $('.waterfall').waterfall(); } </script> </body> </html>