典型实现
function layoutItems(container, items, cols = 3, gap = 16) {
const colHeights = new Array(cols).fill(0);
const colWidth = (container.offsetWidth - (cols - 1) * gap) / cols;
items.forEach((item, i) => {
const minCol = colHeights.indexOf(Math.min(...colHeights));
const top = colHeights[minCol];
const left = minCol * (colWidth + gap);
item.style.width = `${colWidth}px`;
item.style.top = `${top}px`;
item.style.left = `${left}px`;
colHeights[minCol] += item.offsetHeight + gap;
});
container.style.height = Math.max(...colHeights) + 'px';
}
算法要点
- 维护一个数组记录三列的当前高度。
- 每新增一张卡片,就放到“当前最矮的一列”。
- 更新该列的总高度。
- 最终渲染出一个不规则但紧凑的“瀑布流”。
示例站点