示例工程 19-dom-events
19-dom-events/04-intersection-observer/index.html
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>19 · IntersectionObserver 懒加载</title>
<style>
#grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
.card { height: 90px; border: 1px solid #999; display: grid; place-items: center; }
.card.loaded { background: #e8f0ff; }
</style>
</head>
<body>
<p>滚动页面,卡片进入视口后才「加载」。</p>
<div id="grid"></div>
<script type="module">
import { run } from './main.js';
const grid = document.getElementById('grid');
const cards = Array.from({ length: 12 }, (_, i) => {
const el = document.createElement('div');
el.className = 'card';
el.id = `card-${i + 1}`;
el.dataset.src = `/assets/${i + 1}.png`;
el.textContent = `placeholder ${i + 1}`;
grid.appendChild(el);
return el;
});
const loaded = [];
const observer = new IntersectionObserver((entries) => {
for (const entry of entries) {
if (!entry.isIntersecting) continue;
const el = entry.target;
el.classList.add('loaded');
el.textContent = `loaded ${el.dataset.src}`;
loaded.push(el.id);
observer.unobserve(el);
}
}, { threshold: 0.1 });
cards.forEach((card) => observer.observe(card));
setTimeout(() => {
console.log('已加载 =>', loaded);
console.log('已加载数量 =>', loaded.length);
run();
}, 300);
</script>
</body>
</html>