IntersectionObserver
是一个现代浏览器提供的 API,用于监听元素与其祖先元素或顶层文档视窗(viewport)交叉的情况,即元素是否进入或离开视窗。
它通常用于实现懒加载图片、监听滚动事件、触发动画效果等场景,可以显著提高性能和用户体验。
创建 Intersection Observer 实例
const options = {
root: null, // 根元素,默认是视窗 填要观察元素的父级
rootMargin: '0px', // 根元素的边距
threshold: 0.5 // 当目标元素 50% 进入视窗时触发回调
}
const observer = new IntersectionObserver(callback, options)
指定观察目标:
const target = document.querySelector('.target-element')
observer.observe(target)
编写回调函数:
function callback(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 目标元素进入视窗
console.log('目标元素进入视窗')
// observer.unobserve(target) // 假如是懒加载图片 完成加载就不用去监听了
} else {
// 目标元素离开视窗
console.log('目标元素离开视窗')
}
})
}
停止观察:
observer.unobserve(target)
关闭观察器:
observer.disconnect()
<!DOCTYPE html>
<html>
<head>
<title>Intersection Observer 示例</title>
</head>
<body>
<div class="target-element" style="height: 200px; background-color: lightblue;">
目标元素
</div>
<script>
// 创建 Intersection Observer 实例
const options = {
root: null, // 根元素,默认是视窗
rootMargin: '0px', // 根元素的边距
threshold: 0.5 // 当目标元素 50% 进入视窗时触发回调
};
const observer = new IntersectionObserver(callback, options);
// 获取目标元素
const target = document.querySelector('.target-element');
// 指定观察目标
observer.observe(target);
// 编写回调函数
function callback(entries, observer) {
entries.forEach(entry => {
if (entry.isIntersecting) {
// 目标元素进入视窗
console.log('目标元素进入视窗');
target.style.backgroundColor = 'lightgreen'; // 改变背景颜色
} else {
// 目标元素离开视窗
console.log('目标元素离开视窗');
target.style.backgroundColor = 'lightblue'; // 恢复原始背景颜色
}
});
}
</script>
</body>
</html>
const ob = new IntersectionObserver((entries) => {
const entry = entries[0]
const vdo = entry.target
if (entry.isIntersecting) {
vdo.play()
} else {
vdo.pause()
}
}, {
threshold: 1
})
ob.observe(document.querySelector('video'))