console
let waterfall = document.querySelector(".waterfall");
let items = document.querySelectorAll(".item");
const loadMoreButton = document.getElementById('loadMore');
let leftColumnHeight = 0;
let rightColumnHeight = 0;
const min = 50;
const max = 150;
const addList = ['','','','']
let itemCount = 0
function createItem(data) {
const item = document.createElement("div");
const id = itemCount++;
item.id = "Item " + id;
item.className = "item";
item.textContent = "Item " + id;
const randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
item.style.height = randomNum + 'px';
return item;
}
function addTree(data) {
const item = createItem(data);
const id = item.id;
waterfall.appendChild(item);
const targetItem = document.getElementById(id);
const targetHeight = targetItem.offsetHeight;
if (leftColumnHeight <= rightColumnHeight) {
targetItem.style.left = "0";
targetItem.style.top = leftColumnHeight + "px";
leftColumnHeight += targetHeight;
} else {
targetItem.style.left = "50%";
targetItem.style.top = rightColumnHeight + "px";
rightColumnHeight += targetHeight;
}
waterfall.style.height = Math.max(leftColumnHeight, rightColumnHeight) + "px";
}
loadMoreButton.addEventListener("click", () => {
addTree({});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>瀑布流</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="content">
<div class="waterfall">
</div>
</div>
<button id="loadMore">加载更多</button>
<script src="script.js"></script>
</body>
</html>
body {
overflow: hidden;
height: 100%;
}
.content {
min-height: 75vh;
height: 75vh;
overflow: scroll;
}
.waterfall {
position: relative;
}
.item {
position: absolute;
width: calc(50% - 10px);
box-sizing: border-box;
background-color: #f0f0f0;
border: 1px solid #ddd;
padding: 10px;
}
.item:nth-child(6) {
height: 150px;
}