【问题标题】:IntersectionObserver working scrolling down but not scrolling upIntersectionObserver 工作向下滚动但不向上滚动
【发布时间】:2026-02-01 06:55:01
【问题描述】:

我正在使用IntersectionObserver 突出显示当前部分的相应导航项。 除非我向上滚动,否则一切似乎都运行良好。当我这样做时,我刚离开的部分得到isIntersecting: false(应该如此),但我刚输入的部分没有被观察到。 为向上滚动创建一个新的IntersectionObserver 似乎是多余的,而且是错误的,但我不知道如何使代码在两个滚动方向上都工作。

非常感谢您的宝贵帮助!

这里是 JS:

const sections = document.querySelectorAll(".section");
const config = {
  rootMargin: "0px 0px -51%",
};

let observer = new IntersectionObserver(function (entries) {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      intersectionHandler(entry);
    }
  });
}, config);

sections.forEach((section) => {
  observer.observe(section);
});

function intersectionHandler(entry) {
  const id = entry.target.id;
  const currentlyActive = document.querySelector("#nav a.is-selected");
  const shouldBeActive = document.querySelector(
    "#nav a[data-section=" + id + "]"
  );

  if (currentlyActive) {
    currentlyActive.classList.remove("is-selected");
  }
  if (shouldBeActive) {
    shouldBeActive.classList.add("is-selected");
  }
}

【问题讨论】:

  • 您将底部边距设置为-51px,因此当您“向上滚动”时,API 会在确定交点之前不断地从视口底部移除 51px。然后,假设出现下一个<section>,并计算出一个新的交叉点 - 再次,51px 在底部下方。您应该使用阈值 API 功能,而不是设置负边距。
  • 非常感谢!我会试试的。
  • 刚刚更改为const config = {rootMargin: "0px", threshold: 0.5,};,它就像一个魅力!再次感谢!
  • 不客气。如果我将此放在答案中,您会投票并接受吗?
  • 没问题!

标签: javascript scroll intersection-observer


【解决方案1】:

您将底部边距设置为-51px,因此当您“向上滚动”时,API 会在确定交点之前不断地从视口底部移除 51px。然后,假设出现下一个<section>,并计算出一个新的交叉点——再次,51px 在底部下方。您应该使用阈值 API 功能,而不是设置负边距。

【讨论】: