IntersectionObserver接口介绍

IntersectionObserver API 是浏览器提供的一个用于异步观察目标元素其祖先元素或视口(Viewport)交叉状态(即是否进入或离开视口)的接口。在 IntersectionObserver 出现之前,开发者通常需要通过监听 scroll 事件或使用 getBoundingClientRect 方法来判断元素是否进入视口。

IntersectionObserver 的基本用法

(1) 创建观察器

通过 new IntersectionObserver() 创建一个观察器实例。

const observer = new IntersectionObserver(callback, options);
  • callback
    当目标元素的交叉状态发生变化时触发的回调函数。

  • options
    配置对象,用于指定观察器的行为(可选)。

(2) 观察目标元素

通过 observer.observe() 开始观察目标元素。

const target = document.querySelector('.target');
observer.observe(target);

(3) 停止观察

通过 observer.unobserve() 停止观察目标元素。

observer.unobserve(target);

IntersectionObserver 的回调函数

回调函数会在以下情况下触发:

  1. 目标元素进入或离开视口。

  2. 目标元素的交叉比例(intersection ratio)发生变化。

回调函数接收两个参数:

  • entries:一个 IntersectionObserverEntry 对象的数组,每个对象描述了一个目标元素的交叉状态

  • observer:观察器实例本身。

IntersectionObserverEntry 对象的属性

IntersectionObserver 的配置选项

options 是一个可选对象,可以包含以下属性:

const options = {
  root: null, // 视口
  rootMargin: '0px', // 无边距
  threshold: [0, 0.5, 1], // 交叉比例为 0%、50%、100% 时触发回调
};

const observer = new IntersectionObserver(callback, options);

 使用场景

(1) 图片懒加载

当图片进入视口时,动态加载图片。

const images = document.querySelectorAll('img[data-src]');

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      const img = entry.target;
      img.src = img.dataset.src; // 加载图片
      observer.unobserve(img); // 停止观察
    }
  });
});

images.forEach((img) => observer.observe(img));
(2) 无限滚动

当用户滚动到页面底部时,加载更多内容。

const sentinel = document.querySelector('#sentinel');

const observer = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting) {
    loadMoreContent(); // 加载更多内容
  }
});

observer.observe(sentinel);
(3) 广告曝光统计

当广告进入视口时,记录曝光次数。

const ad = document.querySelector('.ad');

const observer = new IntersectionObserver((entries) => {
  if (entries[0].isIntersecting) {
    logAdImpression(); // 记录广告曝光
    observer.unobserve(ad); // 停止观察
  }
});

observer.observe(ad);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值