### 設計思想
> 水往低處流
如下圖,有4列,下一行的第一個盒子總是放在總列高最小的列中。

### 具體實現代碼
```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>
```
效果圖

- 前端
- js學習
- 瀏覽器默認樣式
- webpack+vue
- 個人常用webpack打包依賴
- vue使用學習
- vue源碼學習
- webpack5配置babel
- 瀑布流布局
- 個人常用庫
- 其他
- centos搭建ss服務器
- ios配置Universal Links
- pdf2htmlEX使用
- python
- python操作redis
- linux部署Django
- dateutil庫(datetime模塊的擴展).md
- docker部署django
- mysql
- 基礎知識
- 常用函數
- join關聯查詢技巧
- linux
- shell備份mysql數據庫
- crontab定時任務
- centos7安裝部署gitlab服務器
- nginx安裝配置
- 收藏夾
- python
- 博客
- 工具
- 其他
- 前端