IntersectionObserver一分钟学会,超级简单
IntersectionObserver:监听元素可见性
核心功能
监听目标元素与视口(或指定祖先元素)的交叉状态(是否进入/离开可视区域)。
典型场景
API 详解
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log('元素进入视口:', entry.target);
} else {
console.log('元素离开视口:', entry.target);
}
});
}, {
root: null,
rootMargin: '0px',
threshold: 0.5
});
observer.observe(element);
observer.unobserve(element);
参数详解
root
- 观察的视口容器
值类型 | 默认值 | 说明 |
---|
Element | null | 指定作为观察基准的可滚动祖先元素 |
Document | | 文档对象(罕见使用) |
null (默认) | ✅ | 使用浏览器视口(viewport)作为参照 |
rootMargin
-视口边距扩展
格式 | 示例 | 效果 |
---|
像素值 | '10px' | 四个方向均扩展10px |
百分比 | '5%' | 基于root元素尺寸计算 |
多值语法 | '10px 5% 0 20px' | 上、右、下、左(同CSS margin顺序) |
rootMargin: '130px'

threshold
-触发
值类型 | 示例 | 触发时机 |
---|
number | 0.5 | 当目标元素50%可见时触发(单阈值触发) |
number[] | [0, 0.5, 1] | 分别在完全不可见、50%可见、完全可见时触发(多阈值触发) |
0 (默认) | ✅ | 元素刚进入/离开视口时触发(即使1px交叉) |
threshold: 0.1

entry对象关键属性
属性 | 说明 |
---|
entry.isIntersecting | 是否进入可视区域(布尔值) |
entry.intersectionRatio | 交叉区域的比例(0-1) |
entry.boundingClientRect | 目标元素的边界矩形(类似 getBoundingClientRect() ) |
entry.rootBounds | 根元素的边界矩形(视口或指定祖先元素) |
总结
监听目标 | 元素与视口的交叉状态 |
---|
触发时机 | 交叉比例超过阈值时 |
性能影响 | 极低(异步处理) |
兼容性 | Chrome 51+、Firefox 55+、Edge 15+ |
是否支持祖先观察 | ✅ 可通过 root 指定祖先元素 |
适用场景 | 懒加载、曝光统计、滚动动画 |
IntersectionObserver
:专注可视性检测,适合懒加载和滚动相关交互。- 两者均为 异步 API,不会阻塞主线程,是现代 Web 开发中替代传统
resize
/scroll
事件的最佳选择。 IntersectionObserver
部分兼容 IE(需 polyfill)