Javascript 使用“相交观察者”检测元素是否位于相交左侧视口的上方或下方
我当前正在使用来检测元素何时离开视口。它的设置如下:Javascript 使用“相交观察者”检测元素是否位于相交左侧视口的上方或下方,javascript,intersection-observer,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, t
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)
但我还想知道元素是在视口上方还是下方。有什么方法可以做到这一点吗?似乎(在您的代码中)条目.boundingClientRect.top值在元素位于屏幕下方时为正值,在元素位于屏幕上方时为负值
请在此处查看:
编辑
经过多次尝试后,这一方法确实有效
const observer=new window.IntersectionObserver(([entry])=>{
console.log(entry.boundingClientRect.top)
if(输入。isIntersecting){
console.log('Enter')
位置(“可见”)//如果可见,则执行操作
返回
}
console.log('Leave')
如果(entry.boundingClientRect.top>0){
位置(“下方”)//在下方做事情
}否则{
位置(“以上”)//如果在上面做事情
}
}, {
root:null,
阈值:0,
})
只有在未将rootMargin
值设置为IntersectionObserver中的选项时,才检查entry.boundingClientRect.top
有效。您应该检查条目。请改为isIntersecting
如果需要检查图元是否已通过视口并相交,请使用以下方法:
isIntersecting || boundingClientRect.top < 0
isIntersecting | | boundingClientRect.top<0
在控制台中检查后,entry对象具有许多属性,例如entry.target.offsetHeight
。。。不是一个解决方案,但可能是一个线索