h5新API=>IntersectionObserver

    科技2023-09-29  82

    文章目录

    一、API二、callback 参数三、IntersectionObserverEntry 对象四、实例:惰性加载(lazy load)五、实例:无限滚动 阮一峰大神讲解 网页开发时,常常需要了解某个元素是否进入了"视口"(viewport),即用户能不能看到它。

    传统的实现方法是,监听到scroll事件后,调用目标元素(绿色方块)的getBoundingClientRect()方法,得到它对应于视口左上角的坐标,再判断是否在视口之内。这种方法的缺点是,由于scroll事件密集发生,计算量很大,容易造成性能问题。

    H5新的 IntersectionObserver API可以自动"观察"元素是否可见。由于可见(visible)的本质是,目标元素与视口产生一个交叉区,所以这个 API 叫做"交叉观察器"。

    一、API

    它的用法非常简单。

    var io = new IntersectionObserver(callback, option);

    上面代码中,IntersectionObserver是浏览器原生提供的构造函数,接受两个参数:callback是可见性变化时的回调函数,option是配置对象(该参数可选)。

    构造函数的返回值是一个观察器实例。实例的observe方法可以指定观察哪个 DOM 节点。

    // 开始观察 io.observe(document.getElementById('example')); // 停止观察 io.unobserve(element); // 关闭观察器 io.disconnect();

    上面代码中,observe的参数是一个 DOM 节点对象。如果要观察多个节点,就要多次调用这个方法。

    io.observe(elementA); io.observe(elementB);

    二、callback 参数

    目标元素的可见性变化时,就会调用观察器的回调函数callback。

    callback一般会触发两次。一次是目标元素刚刚进入视口(开始可见),另一次是完全离开视口(开始不可见)。

    var io = new IntersectionObserver( entries => { console.log(entries); } );

    上面代码中,回调函数采用的是箭头函数的写法。callback函数的参数(entries)是一个数组,每个成员都是一个IntersectionObserverEntry对象。举例来说,如果同时有两个被观察的对象的可见性发生变化,entries数组就会有两个成员。

    三、IntersectionObserverEntry 对象

    IntersectionObserverEntry对象提供目标元素的信息,一共有六个属性。

    { time: 3893.92, rootBounds: ClientRect { bottom: 920, height: 1024, left: 0, right: 1024, top: 0, width: 920 }, boundingClientRect: ClientRect { // ... }, intersectionRect: ClientRect { // ... }, intersectionRatio: 0.54, target: element }

    每个属性的含义如下。

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

    上图中,灰色的水平方框代表视口,深红色的区域代表四个被观察的目标元素。它们各自的intersectionRatio图中都已经注明。

    官方文档介绍

    //初始化一个实例 var observer = new IntersectionObserver(changes => { for (const change of changes) { console.log(change.time); // Timestamp when the change occurred // 当可视状态变化时,状态发送改变的时间戳 // 对比时间为,实例化的时间, // 比如,值为1000时,表示在IntersectionObserver实例化的1秒钟之后,触发该元素的可视性变化 console.log(change.rootBounds); // Unclipped area of root // 根元素的矩形区域信息,即为getBoundingClientRect方法返回的值 console.log(change.boundingClientRect); // target.boundingClientRect() // 目标元素的矩形区域的信息 console.log(change.intersectionRect); // boundingClientRect, clipped by its containing block ancestors, // and intersected with rootBounds // 目标元素与视口(或根元素)的交叉区域的信息 console.log(change.intersectionRatio); // Ratio of intersectionRect area to boundingClientRect area // 目标元素的可见比例,即intersectionRect占boundingClientRect的比例, // 完全可见时为1,完全不可见时小于等于0 console.log(change.target); // the Element target // 被观察的目标元素,是一个 DOM 节点对象 // 当前可视区域正在变化的元素 } }, {}); // Watch for intersection events on a specific target Element. // 对元素target添加监听,当target元素变化时,就会触发上述的回调 observer.observe(target); // Stop watching for intersection events on a specific target Element. // 移除一个监听,移除之后,target元素的可视区域变化,将不再触发前面的回调函数 observer.unobserve(target); // Stop observing threshold events on all target elements. // 停止所有的监听 observer.disconnect();

    四、实例:惰性加载(lazy load)

    有时,我们希望某些静态资源(比如图片),只有用户向下滚动,它们进入视口时才加载,这样可以节省带宽,提高网页性能。这就叫做"惰性加载"。

    有了 IntersectionObserver API,实现起来就很容易了。

    function query(selector) { return Array.from(document.querySelectorAll(selector)); } var observer = new IntersectionObserver( function(changes) { changes.forEach(function(change) { var container = change.target; var content = container.querySelector('template').content; container.appendChild(content); observer.unobserve(container); }); } ); query('.lazy-loaded').forEach(function (item) { observer.observe(item); });

    上面代码中,只有目标区域可见时,才会将模板内容插入真实 DOM,从而引发静态资源的加载。

    五、实例:无限滚动

    var intersectionObserver = new IntersectionObserver( function (entries) { // 如果不可见,就返回 if (entries[0].intersectionRatio <= 0) return; loadItems(10); console.log('Loaded new items'); }); // 开始观察 intersectionObserver.observe( document.querySelector('.scrollerFooter') );

    无限滚动时,最好在页面底部有一个页尾栏(又称sentinels)。一旦页尾栏可见,就表示用户到达了页面底部,从而加载新的条目放在页尾栏前面。这样做的好处是,不需要再一次调用observe()方法,现有的IntersectionObserver可以保持使用。

    Processed: 0.019, SQL: 8