html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>瀑布流</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
#container {
position: relative;
}
.box {
float: left;
width: 350px;
padding: 5px;
}
img {
width: 100%;
}
</style>
<body>
<div id="container">
<div class="box">
<img src="C:\Users\JLZ\Pictures\Sketchpad.png">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\cat.jpg">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\th1.jpg">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\test.jpg">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\查看.jpg">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\下载.png">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\th1.jpg">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\test.jpg">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\查看.jpg">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\下载.png">
</div>
<div class="box">
<img src="C:\Users\JLZ\Pictures\test.jpg">
</div>
</div>
</body>
<script>
window.onload = () => {
imgLocation('container', 'box')
}
function imgLocation(parent, content) {
const cparent = document.getElementById(parent)
const ccontent = getChildElement(cparent, content)
const imgWidth = ccontent[0].offsetWidth
const num = Math.floor(document.documentElement.clientWidth / imgWidth)
cparent.style.width = `${imgWidth * num}px`
const BoxHeightArr = []
for (var i = 0; i < ccontent.length; i++) {
if (i < num) {
//第一行的图片
BoxHeightArr.push(ccontent[i].offsetHeight)
// 起初通过.offsetHeight获取的高度与实际高度不一致,原因在于left的div里有img
// 必须等到页面加载完毕之后才能正确获取content的高度,所以在onload方法里获取content高度才是实际的高度
// console.log(ccontent[i].offsetHeight);
}
else {
const minHeight = Math.min.apply(null, BoxHeightArr)
const minIndex = BoxHeightArr.indexOf(minHeight)
//摆放图片的位置
ccontent[i].style.position = 'absolute'
ccontent[i].style.top = minHeight + 'px'
ccontent[i].style.left = ccontent[minIndex].offsetLeft + 'px'
//更新这一列的高度
BoxHeightArr[minIndex] = BoxHeightArr[minIndex] + ccontent[i].offsetHeight
}
}
}
function getChildElement(parent, child) {
const childArr = []
const allChild = parent.getElementsByTagName('*')
for (var i = 0; i < allChild.length; i++) {
if (allChild[i].className === child) {
childArr.push(allChild[i])
}
}
return childArr
}
</script>
</html>