js 浏览器的5种observer 第二种 IntersectionObserver 详解及使用方法

 

IntersectionObserver 是一个现代的浏览器 API,允许开发者在某个元素与其祖先元素或顶层文档视口发生交叉时得到通知。它非常适合实现图片懒加载、无限滚动、广告曝光率等功能。

1. 浏览器的兼容性

IntersectionObserver 目前在大多数现代浏览器中都得到了支持。但是在一些老版本的浏览器,如 IE 中,则没有支持。
点击查看 IntersectionObserver 的兼容性

2. 如何使用?

// 创建一个观察者实例
const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        // entry.isIntersecting 判断目标元素是否在视口中
        if (entry.isIntersecting) {
            console.log('目标元素在视口中!');
        } else {
            console.log('目标元素不在视口中.');
        }
    });
});
// 开始观察某个元素
const targetElement = document.querySelector('.some-class');
observer.observe(targetElement);

// 停止观察
// 如果你不再需要观察某个元素,你可以调用:
observer.unobserve(targetElement);
// 如果你想停止观察所有元素,你可以调用:
observer.disconnect();

// 配置选项
当创建 IntersectionObserver 实例时,你可以提供一个配置对象,该对象有以下属性:
const options = {
    root: document.querySelector('.scroll-container'), // 观察目标的父元素,如果不设置,默认为浏览器视口
    rootMargin: '10px', // 增加或减少观察目标的可见区域大小
    threshold: [0, 0.25, 0.5, 0.75, 1] // 当观察目标的可见比例达到这些阈值时会触发回调函数
};
const observer = new IntersectionObserver(callback, options);

3. 一些常见的应用场景

// 图片懒加载
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const img = entry.target;
            img.src = img.dataset.lazy;
            observer.unobserve(img);
        }
    });
});
document.querySelectorAll('img[data-lazy]').forEach(img => {
    observer.observe(img);
});

// 无线滚动加载
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            loadMoreContent(); // 你的加载更多内容的函数
            observer.unobserve(entry.target); // 如果你只想加载一次,你可以在这里停止观察
        }
    });
});
const loadMoreTrigger = document.querySelector('.load-more-trigger');
observer.observe(loadMoreTrigger);

posted on   完美前端  阅读(1253)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示