企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### 设计思想 > 水往低处流 如下图,有4列,下一行的第一个盒子总是放在总列高最小的列中。 ![](https://img.kancloud.cn/f8/ea/f8eaf41a00d1696e846c7be1e69b42a5_364x196.png) ### 具体实现代码 ```html <!DOCTYPE html> <html> <head> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> </head> <style> html,body{ margin: 0; padding: 0; } .box{ position: relative; } .box>.item{ position: absolute; } .item:nth-child(2n){ background-color: skyblue; height: 200px; } .item:nth-child(2n+1){ background-color: brown; height: 150px; } .item:nth-child(3n){ background-color: gray; height: 250px; } </style> <body> <div class="box"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </body> <script type="text/javascript"> window.onload = function(){ waterFall(); } // 页面尺寸改变时实时触发 window.onresize = function() { //重新定义瀑布流 waterFall(); }; //获取窗口宽度 function getClient() { return { width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight } } function waterFall(){ let that = this; // 1 确定图片的宽度 - 滚动条宽度 var pageWidth = getClient().width; var columns = 4; //设置列数 var gap = 20;//设置水平间隔和垂直间隔 var itemWidth = (pageWidth-(columns-1)*gap)/columns; //得到item的宽度,(总宽度-总间隔宽度)/列数 $(".item").width(itemWidth); //设置到item的宽度 var arr = [];//存放列的累加高度,数组长度为columns $(".box .item").each(function(i){ var height = $(this).height(); if (i < columns) { //第一行按序布局 $(this).css({ top:0, left:itemWidth * i+gap*i }); arr.push(height);//将行高push到数组 } else { // 其他行 // 3 找到数组中最小高度 和 它的索引 var minHeight = arr[0]; var index = 0; for (var j = 0; j < arr.length; j++) { if (minHeight > arr[j]) { minHeight = arr[j]; index = j; } } // 设置下一行的第一个盒子位置,第一个盒子放在总列高最小的列中 $(this).css({ top:arr[index]+gap, left:$(".box .item").eq(index).css("left") }); // 修改最小列的高度 // 最小列的高度 = 当前自己的高度 + 拼接过来的高度 + 间隔 arr[index] = arr[index] + height + gap; } }); } </script> <html> ``` 效果图 ![](https://img.kancloud.cn/6f/f9/6ff93d61baa1650807c83304bec90f5d_365x364.png)