IntersectionObserver

最近看到 IntersectionObserver 这个新增的API,不多说,贴上用法:

var io = new IntersectionObserver( 
            entries => {
                console.log(entries[0].time);
                // Timestamp when the change occurred
                // 当可视状态变化时,状态发送改变的时间戳
                // 对比时间为,实例化的时间,
                // 比如,值为1000时,表示在IntersectionObserver实例化的1秒钟之后,触发该元素的可视性变化

                console.log(entries[0].rootBounds);
                // Unclipped area of root
                // 根元素的矩形区域信息,即为getBoundingClientRect方法返回的值

                console.log(entries[0].boundingClientRect);
                // target.boundingClientRect()
                // 目标元素的矩形区域的信息

                console.log(entries[0].intersectionRect);
                // boundingClientRect, clipped by its containing block ancestors,
                // and intersected with rootBounds
                // 目标元素与视口(或根元素)的交叉区域的信息

                console.log(entries[0].intersectionRatio);
                // Ratio of intersectionRect area to boundingClientRect area
                // 目标元素的可见比例,即intersectionRect占boundingClientRect的比例,
                // 完全可见时为1,完全不可见时小于等于0

                console.log(entries[0].target);
                // the Element target
                // 被观察的目标元素,是一个 DOM 节点对象
                // 当前可视区域正在变化的元素
            },
            {
                threshold: [0, 0.25, 0.5, 0.75, 1],
                // root
                // DOM元素,但默认值为null,也就是视口区域
                // 表示监听的可视区域为整个视口,也就是浏览器的可视区域
                // 如果设置了DOM元素,那么视口就变为该元素(即,就算元素在屏幕的可视区域,但是不在该DOM元素的可视区域,仍然不会触发可视性变化)

                // rootMargin
                // 类似于css的margin属性,可以设置四个属性。
                // 该属性默认值为0px 0px 0px 0px,如果设置之后,会影响触发回调的时间

            }
        );
        // 开始观测某个元素
        io.observe(document.querySelector('.canvas-unit'));
         
        // 停止关注某个元素
        // io.unobserve(element);
         
        // 禁用整个 IntersectionObserver
        // io.disconnect();

 

兼容性确实也不算很好,但是常用的webkit内核算是覆盖全了:

 

posted @ 2019-04-17 19:30  herorest  阅读(283)  评论(0编辑  收藏  举报