← 返回首页

移动端瀑布流:手写一个短短的 Masonry

博客的卡片高度参差不齐,用 Grid 会留下难看的空白,用 column-count 又会让阅读顺序变成"竖着读"。

最后选了最笨也最可控的做法:按列高最短优先摆放。

const heights = new Array(cols).fill(0);
items.forEach((item) => {
  item.style.width = colWidth + "px";
  const target = heights.indexOf(Math.min(...heights));
  item.style.transform =
    `translate(${target * (colWidth + gap)}px, ${heights[target]}px)`;
  heights[target] += item.offsetHeight + gap;
});

动态加载

滚动到底部时用 IntersectionObserver 观察一个哨兵元素,触发 fetch 拉下一批:

const io = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting) loadMore();
}, { rootMargin: "300px 0px" });
io.observe(document.getElementById("sentinel"));

接口直接返回渲染好的 HTML 片段,前端 appendChild 即可,省掉一套前端模板。

一点体会

  • 图片一定要给宽高比,否则瀑布流会抖动
  • 新卡片先透明再淡入,观感差别很大
  • 手机上别做无限滚动 + 底部导航,容易误触