WebAPI:IntersectionObserver ,观察容器的交叉重叠 Nov 20 2024 笔记 0 comment `IntersectionObserver`API 提供了一种异步观察元素与其祖先元素或者顶级文档视口(view port)交叉重叠状态,这个祖先元素或顶级视口被称为root。 ### 1. 构造函数new IntersectionObserver(callback, options) 当一个IntersectionObserver对象被创建,它监听root的一段给定比例的可见区域。观察对象被创建后就无法改变其监视区域了,但同一个观察者对象中可配置监听多个目标元素。 创建IntersectionObserver对象的示例: const IntersectionObserver = new IntersectionObserver(entries => { console.log(entries) }, { root:null, threshold:0 } ); IntersectionObserver.observe(document.querySelector('.element1')); IntersectionObserver.observe(document.querySelector('.element2')); ### 2. 配置参数options - **root**:被观察的目标元素的交叉对象元素,当配置为`null`时为文档视口。 - **threshold**:触发回调函数的阈值列表,列表中的每个阈值都是监听对象的交叉区域与边界区域的比率,按升序排列。默认值为`0`。 - **rootMargin**:观察范围的偏移量。通过设定该配置给root添加额外偏移的识别区域。可以有效的缩小或扩大 root 的判定范围从而满足计算需要。默认值`0px 0px 0px 0px`,单位`px`或`%`。 threshold示意图如下  rootMargin示意图如下  ### 3. 回调函数callback 被观察元素每次与root交叉重叠均会触发回调函数,通过回调函数可以获得被观察对象与root交叉关系的目标信息`entries`。  `entries`项说明: | boundingClientRect | 观察目标元素的边界信息,与element.getBoundingClientRect() 相同 | | ------------------ | ------------------------------------------------------------ | | intersectionRatio | **观察目标元素与root的交叉重叠比率** | | intersectionRect | **观察目标元素与root的相交区域** | | isIntersecting | **观察目标是否在root内;如果观察目标出现在root可视区,返回true。 如果从root可视区消失,返回false**** | rootBounds | **用来描述交叉区域观察者(intersection observer)中的根.** | | target | **目标元素:与根出现相交区域改变的元素 (Element)** | | time | **返回一个记录从` IntersectionObserver` 的时间原点到交叉被触发的时间的时间戳** | ### 4. 示例与验证 <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <style> body{ margin: 0; background: #000; display: flex; justify-content: center; align-items: center; } .root{ height: 600px; width: 400px; border: 2px solid #1fe50b; overflow-y: scroll; } .root .app{ height: 2000px; } .root .app .element{ height: 200px; border: 2px solid tomato; margin-top: 100px; } </style> <body> <div class="root"> <div class="app"> <div class="element"></div> </div> </div> <script> const observer = new IntersectionObserver(entries => { console.log(entries) }, { root: document.querySelector('.root'), threshold: 0.1 } ); const element = document.querySelector('.element'); observer.observe(element); </script> </body> </html> 这里设置绿色盒子为root,红色盒子为被观察目标。root内设置为scroll,当红色盒子通过滚动离开和再次进入时,都会根据options的threshold来触发回调函数。 观察输出: - 当下滑,红色盒子离开绿色盒子时:即第一次控制台打印,isIntersecting为false,表示观察目标离开root可视区域、intersectionRatio是一个接近我们设置的threshold的值0.1。 - 当上滑,红色盒子进入绿色盒子时:即第二次控制台打印,isIntersecting为true,表示观察目标进入root可视区域、intersectionRatio是一个接近我们设置的threshold的值0.1。 本文由 yuin 创作,本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。