效果、原理
源码
* {
padding: 0;
margin: 0;
box-sizing: border-box;
outline: none;
}
html,
body {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
}
#app {
position: relative;
width: 100vw;
height: 100vh;
overflow: auto;
}
.pic-item {
position: absolute;
border: 1px solid #000;
}
<div id="app">
</div>
const root = document.getElementById('app');
for (let i = 1; i <= 20; i++) {
const color = ()=>{
let c = '0123456789abcdef'.split('');
return c[Math.floor(Math.random(0, 1) * 15)];
}
let h = Math.floor(Math.random() * 500) + 50;
let img = document.createElement("img");
img.className = 'pic-item';
img.width = 200;
img.src = `https://dummyimage.com/200x${h}/${color()}${color()}${color()}/fff?text=200x${h} ${i}`;
root.appendChild(img);
}
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
const picList = document.getElementsByClassName('pic-item');
const w = 200;
const col = 5;
let heightList = [...picList].slice(0, col).map(el => el.offsetHeight);
console.log(`第一行 ${
col} 个 图片标签的高度`, heightList);
for (let i = 0; i < picList.length; i++) {
let ele = picList[i];
if (i < col) {
ele.style.top = '0px';
ele.style.left = `${
w * i}px`;
}
else {
let minHeight = Math.min.apply(null, heightList);
let j = heightList.indexOf(minHeight);
ele.style.top += `${
minHeight}px`;
ele.style.left = `${
w * j}px`;
heightList[j] += ele.offsetHeight;
console.log('修改最小高度后新的高度集合', heightList);
}
}
}
}