现象:懒加载图片一直不显示,isIntersecting 始终 false
给图片列表加 IntersectionObserver 做懒加载,图片明明在视口里但回调里 isIntersecting 每次都是 false,src 拿不到。Console 打印了位置信息,确实和 root 有重叠。排查发现是 threshold 设成 [1.0],但顶部导航栏压了 10%,实际只 90% 可见。
根因:threshold 设太高,实际交集比例没达标
threshold 数组定义回调触发的时机——target 和 root 的交集占自身比例。[1.0] 要求 100% 可见,但导航栏挡住就永远达不到。另一个常见坑是 rootMargin 没留缓冲,图片刚进视口就触发又离开。
// 错误:threshold 太高
{ threshold: [1.0] }
// 正确:0.01 一像素就触发,rootMargin 底部预加载 200px
const io = new IntersectionObserver(entries => {
entries.forEach(e => {
if (e.isIntersecting) {
e.target.src = e.target.dataset.src;
io.unobserve(e.target); // 加载完停,别反复触发
}
});
}, { threshold: 0.01, rootMargin: '0px 0px 200px 0px' });
排查顺序:threshold → rootMargin → root → target
第一查 threshold:设 0 或 [0, 0.01],确保任何可见都能触发。第二查 rootMargin:给 bottom/top 加几百像素缓冲。第三查自定义 root:确认它不是 display:none、没显式高度、overflow 不是 hidden。第四查 target:transform 或 position: fixed 有时让 IO 算错位置,先去掉试试。
// 调试:打印每次回调的关键字段
const io = new IntersectionObserver(entries => {
entries.forEach(e => {
console.log('intersectionRatio:', e.intersectionRatio);
console.log('boundingClientRect:', e.boundingClientRect);
console.log('rootBounds:', e.rootBounds);
});
}, { threshold: [0, 0.25, 0.5, 0.75, 1.0] });
兼容性兜底
IntersectionObserver Chrome 51+、Safari 12.1+、Edge 15+ 全支持。老版 iOS Safari 12.0 及以下不支持,加个 if ('IntersectionObserver' in window) 判断,不支持就用 scroll + getBoundingCLIentRect 兜底。
总结:isIntersecting 始终 false 八成是 threshold 太高。改成 0.01 起步,加 rootMargin 预加载缓冲。调试时打印 intersectionRatio 和 boundingClientRect,快速定位是阈值问题还是被导航栏挡住了。
