【问题标题】:Intersection observer API scroll aware navigationIntersection Observer API 滚动感知导航
【发布时间】:2026-02-14 07:20:03
【问题描述】:

我正在尝试使用交叉点观察器来创建类似于下面的网站链接的内容,整个目的是重新创建用作每个部分导航的粘性框,我对此的思考过程与导航栏有关当它进入时更改活动部分,附加到我的代码笔的链接图片还显示了我在主站点上尝试实现的目标我从网站链接中得到了这个想法, 密码笔:https://codepen.io/thatfemicode/pen/JjWRNoZ 附加链接:https://olaolu.dev/

Javascript

 const changeNav = (entries, observer) => {
      entries.forEach((entry) => {
        // verify the element is intersecting
        if (entry.isIntersecting && entry.intersectionRatio >= 0.55) {
          // remove old active class
          document.querySelector(".active").classList.remove("active");
          // get id of the intersecting section
          var id = entry.target.getAttribute("id");
          // find matching link & add appropriate class
          var newLink = document
            .querySelector(`[href="#${id}"]`)
            .classList.add("active");
        }
      });
    };
    
    // init the observer
    const options = {
      threshold: 0.55,
    };
    
    const observer = new IntersectionObserver(changeNav, options);
    
    // target the elements to be observed
    const sections = document.querySelectorAll("section");
    sections.forEach((section) => {
      observer.observe(section);
    });

【问题讨论】:

  • 您是否要修复一些错误?
  • 不,基本上我正在尝试创建充当每个框的固定框,我希望我可以添加一张图片来说明我正在尝试做的事情,在我的 codepen 演示中,我当一个部分进入视口时,使用交叉点观察器来更改活动类,这也是我试图用固定框实现的,当一个部分进入 codepen 时,如果你看,该部分 id 的框会发生变化在页面的右下角,当你在olaolu.dev这个网站上向下滚动时,请注意这里的操作。 @lissettdm

标签: javascript css frontend intersection-observer


【解决方案1】:

在该脚本中将 newLink 行更改为:

var newLink = document.querySelector('[href="#'+id+'"]').classList.add('active');

【讨论】: