原理
图片定位:
position:absolute;
top:最小图片的高度;
left:最小图片索引*图片的宽度
<!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 {
position: relative;
}
.img div {
width: 22rem;
float: left;
}
.img img {
width: 22rem;
height: auto;
}
</style>
</head>
<body>
<div class="img">
<div><img src="./img/img (1).jpg" alt=""></div>
<div><img src="./img/img (2).jpg" alt=""></div>
<div><img src="./img/img (3).jpg" alt=""></div>
<div><img src="./img/img (4).jpg" alt=""></div>
<div><img src="./img/img (5).jpg" alt=""></div>
<div><img src="./img/img (6).jpg" alt=""></div>
<div><img src="./img/img (7).jpg" alt=""></div>
<div><img src="./img/img (8).jpg" alt=""></div>
<div><img src="./img/img (9).jpg" alt=""></div>
<div><img src="./img/img (10).jpg" alt=""></div>
<div><img src="./img/img (11).jpg" alt=""></div>
<div><img src="./img/img (12).jpg" alt=""></div>
</div>
</body>
<script>
window.onload = function () {
this.pubu();
}
function pubu() {
let imgs = document.getElementsByTagName('img')
imgs = [...imgs]
let imgW = imgs[0].offsetWidth //当前图片宽度
let windowW = window.innerWidth //当前屏幕宽度
let cols = parseInt(windowW / imgW) //列数
let heightArr = []
// 遍历第一排不需要定位
for (let i = 0; i < imgs.length; i++) {
// heightArr.push(imgs[i].height)
var imgH = imgs[i].height;
if (i < cols) { //是不是第一排
heightArr[i] = imgH;
} else {
// 求出数组最小值
var minImgH = Math.min(...heightArr);
console.log(heightArr);
var index = heightArr.findIndex((value) => {
return value == minImgH
})
imgs[i].style.position = 'absolute';
imgs[i].style.left = index * imgW + 'px';
imgs[i].style.top = minImgH + 'px';
}
// 高度追加
heightArr[index] += imgH;
}
}
</script>
</html>
实现效果