<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
<script src="lib/base.js"></script>
<title>Document</title>
<style>
* {
margin: 0;
padding: 0
}
img {
width: 240px;
}
.item {
border: 1px solid rgb(131, 130, 130);
padding: 20px;
float: left;
}
</style>
</head>
<body>
<div class="content">
<div class="item">
<img src="images/01.jpg" alt="">
</div>
<div class="item">
<img src="images/02.jpg" alt="">
</div>
<div class="item">
<img src="images/03.jpg" alt="">
</div>
<div class="item">
<img src="images/04.jpg" alt="">
</div>
<div class="item">
<img src="images/05.jpg" alt="">
</div>
<div class="item">
<img src="images/06.jpg" alt="">
</div>
<div class="item">
<img src="images/07.jpg" alt="">
</div>
<div class="item">
<img src="images/08.jpg" alt="">
</div>
<div class="item">
<img src="images/09.jpg" alt="">
</div>
<div class="item">
<img src="images/10.jpg" alt="">
</div>
<div class="item">
<img src="images/11.jpg" alt="">
</div>
<div class="item">
<img src="images/12.jpg" alt="">
</div>
</div>
<script>
/* 假设是从服务器取得的数据 */
var url = {
dataUrl: [{
src: "01.jpg"
}, {
src: "02.jpg"
}, {
src: "03.jpg"
}, {
src: "04.jpg"
}, {
src: "05.jpg"
}, {
src: "06.jpg"
}, {
src: "07.jpg"
}, {
src: "08.jpg"
}, {
src: "09.jpg"
}, {
src: "10.jpg"
}, {
src: "11.jpg"
}, {
src: "12.jpg"
}]
}
/* 1.一排能放置几张图片 */
window.onload = function () {
place_img();
url.dataUrl.forEach(item => {
let list = `<div class="item"><img src="images/${item.src}"/></div>`
$(".content").append(list);
place_img()
})
}
function place_img() {
var ww = $(window).width()
var itemWidth = $(".item").outerWidth();
var num = Math.floor(ww / itemWidth);
/* 2.将第一排的高度放置在一个数组中 */
var arrHeight = []
$(".item").each((index, item) => {
if (index < num) {
var itemHeight = $(item).outerHeight();
arrHeight.push(itemHeight)
} else {
/* 3.从高度最小的地方开发放置图片 */
var minHeight = Math.min(...arrHeight);
var minIndex = arrHeight.indexOf(minHeight);
var offsetLeft = $(".item").eq(minIndex).offset().left;
$(".item").eq(index).css({
position: 'absolute',
top: minHeight,
left: offsetLeft
})
/* 4.重置数组中的最小高度 */
arrHeight[minIndex] = minHeight + $(".item").eq(index).outerHeight();
}
})
}
</script>
</body>
</html>