详解 Intersection Observer API ( 交叉观察器 )

一、介绍

Intersection Observer API 提供了一种方法可以监听目标元素是否展示到视口(viewport,常见的需求场景:

  • 图片懒加载
  • 滚动动画

上述的需求,以往一般监听 scroll 事件,利用 getBoundingClientRect()方法获取目标元素的位置信息。由于监听 scroll 事件,不断地触发回流,对性能有一定的影响,不过可以通过函数节流解决,但是 getBoundingClientRect() 方法对性能造成的影响无法有效优化的。

!!!所以,浏览器为了解决上述难题,推出了IntersectionObserver API ,由于方法是异步的,不影响主线程的执行效率。

二、兼容性

兼容市面的主流浏览器,总体来说乐观,不过为了代码的严谨,简单判断下:

if (window?.IntersectionObserver) {
	let io = new IntersectionObserver(callback, options)
	io.observe(targetElement)
}

在这里插入图片描述

三、内置方法/属性

let io = new IntersectionObserver(entries => {
	// IntersectionObserverEntry 作为一个参数返回
	console.log(entries)
}, { root: null, rootMargin: '0px 0px', threshold: [0.5, 1] })

// 开始监听
io.observe(targetElement)
// 停止监听
io.unobserve(targetElement)
// 结束监听器
io.disconnect()

以上我们可以看到,IntersectionObserver 接收一个回调函数,和一个对象options作为参数。

IntersectionObserverEntry 实例作为entries参数被传递到回调函数,提供此时元素的相关信息。


查看 entries 具有哪些属性:

在这里插入图片描述

属性作用
boundingClientRect目标元素的矩形区域的信息
intersectionRatio目标元素的可见比例,即 intersectionRectboundingClientRect 的比例,完全可见时为1,完全不可见时小于等于0
intersectionRect目标元素与视口(或根元素)的交叉区域的信息
isIntersecting目标目标元素是否已转换为相交状态(true)或已转换为不相交状态(false
rootBounds根元素的矩形区域的信息,getBoundingClientRect()方法的返回值,如果没有根元素(即直接相对于视口滚动),则返回null
target被观察的目标元素,是一个 DOM 节点对象
time可见性发生变化的时间,是一个高精度时间戳,单位为毫秒

API 提供的方法/属性:

方法 / 属性作用
root 根元素,默认视口(viewport)
rootMargin相对根元素的偏移量,默认值为"0px 0px"
threshold触发回调函数的门阀值,升序排列,默认0,可选:[0, 0.25, 0.5, 0.75, 1]
observe(targetElement)开始监听,必传 targetElement,可同时观察多个节点
unobserve(targetElement)停止监听,必传 targetElement
takeRecords()为所有监听目标返回一个IntersectionObserverEntry对象数组并且停止监听这些目标
disconnect()停止监听器工作

四、使用

我们这里写一个滚动更新元素内容/样式功能:
在这里插入图片描述

HTML:

<div class="container">
  <div class="item" data-id="1">元素1:不可见</div>
  <div class="item" data-id="2">元素2:不可见</div>
  <div class="item" data-id="3">元素3:不可见</div>
  <div class="item" data-id="4">元素4:不可见</div>
  <div class="item" data-id="5">元素5:不可见</div>
</div>

JS: 当目标元素完全暴露/非完全暴露时,修改文字/背景颜色

<script>
  if (window?.IntersectionObserver) {
    let items = [...document.getElementsByClassName('item')] // 解析为真数组,也可用 Array.prototype.slice.call()

    let io = new IntersectionObserver(entries => {
      entries.forEach(item => {
        // intersectionRatio === 1说明该元素完全暴露出来
        if (item.intersectionRatio === 1) {
          item.target.style.backgroundColor = 'deeppink'
          item.target.innerHTML = `元素${item.target.getAttribute('data-id')}:完全可见`
        } else {
          item.target.style.backgroundColor = 'deepskyblue'
          item.target.innerHTML = `元素${item.target.getAttribute('data-id')}:不可见`
        }
      })
    }, {
      root: null,
      rootMargin: '0px 0px',
      threshold: 1 // 阀值设为1,当只有比例达到1时才触发回调函数
    })

    items.forEach(item => io.observe(item))
  }
</script>

五、相关链接

  • 5
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端小小白zyw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值