使用相交观察者检测相交离开时元素是高于还是低于视口

bra*_*cho 4 javascript intersection-observer

我目前正在使用相交观察器来检测元素何时离开视口。它是这样设置的:

const el = document.querySelector('#el')
const observer = new window.IntersectionObserver(([entry]) => {
  if (entry.isIntersecting) {
    console.log('LEAVE')
    return
  }
  console.log('ENTER')
}, {
  root: null,
  threshold: 0,
})

observer.observe(el)
Run Code Online (Sandbox Code Playgroud)

但我也想知道元素是在视口上方还是下方。有没有办法实现这一目标?

gui*_*ui3 15

似乎(使用您的代码)entry.boundingClientRect.top当元素低于屏幕时该值为正值,而当元素高于屏幕时该值为负值

在这里检查:https : //codepen.io/gui3/pen/VwwRORL

_ 编辑 _ 经过多次尝试,这确实有效

const observer = new window.IntersectionObserver(([entry]) => {
  console.log(entry.boundingClientRect.top)
  if (entry.isIntersecting) {
    console.log('Enter')
    position("VISIBLE") // do things if visible
    return
  }
  console.log('Leave')
  if (entry.boundingClientRect.top > 0) {
    position("BELOW") // do things if below
  } else {
    position("ABOVE") // do things if above
  }
}, {
  root: null,
  threshold: 0,
})
Run Code Online (Sandbox Code Playgroud)