【问题标题】:Detect whether element is above or below the viewport on intersect leave with intersection observer在与交叉点观察者相交离开时检测元素是高于还是低于视口
【发布时间】:2023-03-27 17:36:05
【问题描述】:

我目前正在使用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)

但我也想知道元素是在视口上方还是下方。有没有办法做到这一点?

【问题讨论】:

  • 在控制台中检查后,entry 对象具有 a lot 的属性,例如 entry.target.offsetHeight ... 不是解决方案,但是也许是线索

标签: javascript intersection-observer


【解决方案1】:

似乎(使用您的代码)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,
})

【讨论】:

  • 这很好用,但是如果交叉点正好在 div 的中间,而不是一直在上方或下方,你想做什么呢?
【解决方案2】:

检查entry.boundingClientRect.top只有在您没有将rootMargin 值设置为IntersectionObserver 中的选项时才有效。你应该检查entry.isIntersecting

如果您需要检查元素是否已通过视口并相交,请使用此:

isIntersecting || boundingClientRect.top < 0

【讨论】:

    【解决方案3】:

    这很简单

    let scrollY = window.scrollY;
    
    new IntersectionObserver(([entry]) => {
      if (!entry.isIntersecting) {
        if (window.scrollY > scrollY) {
          // entry is above
        } else {
          // entry is below
        }
      }
      scrollY = window.scrollY;
    }, {
      threshold: [0.4]
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-17
      • 2022-01-23
      • 1970-01-01
      • 2018-11-22
      • 2021-07-20
      • 1970-01-01
      • 2022-01-17
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多