2021年1月3日,今天又是充满希望的一天。
html
<body>
<div id="main">
<div class="box">
<!-- 模拟图片 -->
<div style="height: 400px; background-color: aqua;">1</div>
</div>
<div class="box">
<div style="height: 200px; background-color: red;">2</div>
</div>
<div class="box">
<div style="height: 100px; background-color: gray;">3</div>
</div>
<div class="box">
<div style="height: 500px; background-color: blue;">4</div>
</div>
<div class="box">
<div style="height: 200px; background-color: yellow;">5</div>
</div>
<div class="box">
<div style="height: 300px; background-color: gold;">6</div>
</div>
<div class="box">
<div style="height: 100px; background-color: aquamarine;">7</div>
</div>
</div>
</body>
css
<style>
#main {
position: relative;
margin: 0 auto;
}
.box {
width: 200px;
padding: 10px;
}
.box>div {
padding: 10px;
}
</style>
js
<script>
function waterFall() {
const boxes = document.getElementsByClassName('box')
const length = boxes.length
const boxWidth = boxes[0].offsetWidth
const bodyWidth = document.body.clientWidth
// 计算展示多少列
const cols = parseInt(bodyWidth / boxWidth)
// 主容器样式添加了margin:0 auto,现在设置主容器的宽度,让它居中对齐
const mainDom = document.getElementById('main')
mainDom.style.width = cols*boxWidth + 'px'
// 数组用于存放每一列的高度
const heightArr = []
for (let index = 0; index < length; index++) {
const box = boxes[index]
const boxHeight = box.offsetHeight
// 第一行
if (index < cols) {
heightArr[index] = boxHeight
box.style.position = 'absolute'
box.style.left = index * boxWidth + 'px'
box.style.top = '0px'
} else { // 第二行及以上
// 找出高度最小的那一列,将当前box排在这一列
const minBoxHeight = Math.min(...heightArr)
const minBoxIndex = heightArr.indexOf(minBoxHeight)
box.style.position = 'absolute'
box.style.left = minBoxIndex*boxWidth + 'px'
box.style.top = minBoxHeight + 'px'
// 这一列排入当前box后,增加当前box的高度
heightArr[minBoxIndex] += box.offsetHeight
}
}
}
// 等整个页面渲染完成,图片等资源加载完成
window.onload = function () {
waterFall()
}
window.onresize = function () {
waterFall()
}
</script>