如何判断元素是否在可视区域?
参考答案
1. IntersectionObserver(推荐)
const io = new IntersectionObserver(([en]) => { if (en.isIntersecting) {} }, { root: null, threshold: 0.1 });
io.observe(el);
不阻塞主线程、支持阈值与 rootMargin,适合懒加载/曝光统计。
2. getBoundingClientRect
const r = el.getBoundingClientRect();
const visible = r.top < window.innerHeight && r.bottom > 0 && r.left < window.innerWidth && r.right > 0;
注意会触发强制同步布局,频繁调用需节流/rAF。
3. 传统计算
el.offsetTop < scrollTop + clientHeight && el.offsetTop + el.offsetHeight > scrollTop(受嵌套定位影响,需累加 offsetParent)。
4. 其他
document.elementFromPoint 判断可见性;el.checkVisibility()(新 API)。