使用IntersectionObserver进行曝光打点

在网页开发中,IntersectionObserver API用于检测元素是否进入或离开视口,实现智能加载、滚动动画等效果。该API接受回调函数和配置对象作为参数,回调函数会在元素的可视状态改变时触发,返回IntersectionObserverEntry对象,包含如时间戳、目标元素、可见比例等信息。通过调用observe和unobserve方法,可以开始和停止对特定元素的观察,而disconnect则关闭整个观察器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网页开发时,常常需要了解某个元素是否进入了"视口"(viewport),即用户能不能看到它。

IntersectionObserver是浏览器原生提供的构造函数:

import'intersection-observer';
export default {
    async mounted() {
        await this.$nextTick()
        var io = new IntersectionObserver(entries => {
            console.log(entries)
        },{
            threshold: [0, 0.25, 0.5, 0.75, 1]
        });
        io.POLL_INTERVAL = 100; // Time in milliseconds.
        io.observe(this.$refs.content)

    }
}

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

   intersection-observer是做兼容处理的。

// 开始观察
io.observe(document.getElementById('example'));

// 停止观察
io.unobserve(element);

// 关闭观察器
io.disconnect();

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

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

参考:https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值