Javascript 如何确定滚动时是否传递了元素?

Javascript 如何确定滚动时是否传递了元素?,javascript,scroll,Javascript,Scroll,我试图找出我在滚动时什么时候通过了某些元素 const elementTarget = document.getElementById('sidebar'); window.addEventListener('scroll', () => { if (window.scrollY > elementTarget.offscrollTop) { console.log('passed an element'); } }) 示例代码: 编辑:

我试图找出我在滚动时什么时候通过了某些元素

  const elementTarget = document.getElementById('sidebar');

  window.addEventListener('scroll', () => {
    if (window.scrollY > elementTarget.offscrollTop) {
      console.log('passed an element');
    }
  })
示例代码:

编辑:
上面的代码不起作用。当我向下滚动并且滚动大于侧边栏元素的偏移量时,条件不会触发。我做错了什么?

getBoundingClientRect()替换
offscrollTop
。top

const elementTarget = document.getElementById("sidebar");

window.addEventListener("scroll", () => {
  if (window.scrollY > elementTarget.getBoundingClientRect().top) {
    console.log("passed an element");
  }
});

首先,必须使用相同id的元素; 其次,您需要使用.offsetTop来获取offset的值

if (window.scrollY > elementTarget1.offsetTop) {
  console.log('passed an element');
}

查看IntersectionObserver您应该熟悉在函数中记录预期结果并检查控制台中的结果
console.log(elementTarget.offscrollTop)
未定义,因为该属性无效。事件触发得太早。当控制台记录传递的时,它还没有到达元素…当你说元素被传递时,你的意思是它开始从屏幕顶部溢出?是的,这就是我的意思。尝试将
if(window.scrollY>elementTarget.getBoundingClientRect().top)
替换为
if(elementTarget.getBoundingClientRect().top<0)
如果(window.scrollY>elementTarget.getBoundingClientRect().top)传递的元素在滚动到元素之前显示得太早,则使用上一个代码。你知道怎么修吗?