<div id="masonry" style="display: grid; place-items: center">
  <h1 style="height: 50vh">IntersectionObserver</h1>
  <h1 style="height: 50vh">向下滚动</h1>
</div>
<div id="masonryFooter">到底了~</div>
// 无限滚动
// 这个例子的缺点是,如果底部元素一开始就是可见的,那么不会触发回调函数
// 只有从不可见变为可见时,才触发加载
const io = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    // 不可见时,返回
    if (entry.intersectionRatio === 0) return;
    // 如果瀑布流的底部可见,则触发加载
    loadItem();
  });
});

io.observe(document.querySelector("#masonryFooter"));

let counter = 0;
function loadItem() {
  if (counter > 10) return;
  const h1 = document.createElement("h1");
  h1.innerHTML = ++counter;
  document.querySelector("#masonry").appendChild(h1);
}

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.