vue滚动时查看滚动到了哪个div

本文介绍了如何在Vue组件的mounted生命周期中使用IntersectionObserverAPI,监控`.section`元素在视窗中的可见性变化,以便于实现动态的滚动导航或内容加载优化。
摘要由CSDN通过智能技术生成
    /* 比如你有若干个div 名字都叫section */

      <div class="section"></div>
      <div class="section"></div>
      <div class="section"></div>
      <div class="section"></div>
      <div class="section"></div>
      <div class="section"></div>

2. 在vue的mounted生命周期中

mounted(){
      this.$nextTick(() => {
      const options = {
        root: null, // 指定根元素,这里设为 null,表示选取整个视窗作为根元素。
        rootMargin: "0px", // 指定根元素的边界,这里设为 "0px",表示根元素的边界和视窗的边界重合
        threshold: 0.5, // 指定交叉比例,这里设为 0.5,表示当目标元素一半或更多显示在视窗中时触发回调函数。
      };

      const callback = (entries, observer) => {
        //entries:代表观察到的目标元素的集合。 observer:代表观察者对象。

        entries.forEach((entry) => {
          //entry.isIntersecting:检查当前目标元素是否与根元素相交。
          if (entry.isIntersecting) {
            const target = entry.target;
            //entry.target:获取当前目标元素
            const sections = Array.from(document.querySelectorAll(".section"));
            //sections:获取所有具有 .section 类名的元素,并转换为数组。
            let index = sections.findIndex((section) => section === target) + 1;
            //index:查找当前目标元素在 sections 数组中的索引,并加 1,用于确定当前页码。
          }
        });
      };
      // 创建一个新的 Intersection Observer 实例,用于观察目标元素和执行相应的回调函数。
      // new IntersectionObserver(callback, options):使用之前定义的 callback 回调函数和 options 配置选项来初始化 Intersection Observer 实例。
      // javascript

      const observer = new IntersectionObserver(callback, options);

      const sections = document.querySelectorAll(".section");
      //observer 观察每个元素,以便在它们进入或离开视窗时触发回调函数。
      sections.forEach((section) => {
        observer.observe(section);
      });
    });

}

3. 在上面的代码中index 就是进入了当前某个页面 1、2、3、4、5.....

  • 15
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值