示例工程 19-dom-events

19-dom-events/04-intersection-observer/main.js

javascript · 1.1 KB

运行:19 · IntersectionObserver 懒加载

点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。

// main.js —— IntersectionObserver 的纯逻辑部分:从 entry 里挑出可见元素
export function selectVisible(entries, threshold = 0.1) {
  return entries
    .filter((entry) => entry.isIntersecting && entry.intersectionRatio >= threshold)
    .map((entry) => entry.target.id);
}
 
export function summarize(entries, threshold = 0.1) {
  const visible = selectVisible(entries, threshold);
  return {
    total: entries.length,
    visible,
    hidden: entries.length - visible.length,
  };
}
 
export function run(log = console.log) {
  const entries = [
    { isIntersecting: true, intersectionRatio: 1, target: { id: 'a' } },
    { isIntersecting: true, intersectionRatio: 0.2, target: { id: 'b' } },
    { isIntersecting: false, intersectionRatio: 0, target: { id: 'c' } },
    { isIntersecting: true, intersectionRatio: 0.05, target: { id: 'd' } },
  ];
  const result = summarize(entries, 0.1);
  log(`可见并达到阈值:${result.visible.join(', ')}`);
  log(`未触发:${result.hidden} 个`);
  log('IntersectionObserver 在元素进入视口时回调,适合懒加载与曝光统计。');
  return result;
}