瀑布流布局

window.onload = function() {
  const waterfall = document.getElementById('waterfall');
  const items = waterfall.querySelectorAll('.waterfall-item');
  const columnCount = 3;
  const columnHeights = new Array(columnCount).fill(0);

  for (let i = 0; i < items.length; i++) {
    const item = items[i];
    const columnIndex = i % columnCount;
    const columnHeight = columnHeights[columnIndex];
    item.style.left = `${columnIndex * (item.offsetWidth + 10)}px`;
    item.style.top = `${columnHeight}px`;
    columnHeights[columnIndex] += item.offsetHeight + 20;
  }

  const maxHeight = Math.max(...columnHeights);
  waterfall.style.height = `${maxHeight}px`;
};
posted @ 2023-04-11 11:11  jialiangzai  阅读(37)  评论(0)    收藏  举报