Javascript 使用intersectionObserver检查元素是否可见
在我的next.js组件布局中,我试图检查包含div#snipcart的模式窗口何时在窗口中可见 我正在尝试使用IntersectionObserver来检查这一点,但没有得到输出 在我的应用程序中,当屏幕上出现Javascript 使用intersectionObserver检查元素是否可见,javascript,reactjs,next.js,Javascript,Reactjs,Next.js,在我的next.js组件布局中,我试图检查包含div#snipcart的模式窗口何时在窗口中可见 我正在尝试使用IntersectionObserver来检查这一点,但没有得到输出 在我的应用程序中,当屏幕上出现div#snipcart时,我如何检查 useEffect(() => { const cartTotal = document.querySelector('#cartTotal') !== null ? document.querySelector('#cartTot
div#snipcart
时,我如何检查
useEffect(() => {
const cartTotal = document.querySelector('#cartTotal') !== null ? document.querySelector('#cartTotal').textContent.replace('£','') : ''
const cartInvoiceNo = document.querySelector('#invoiceNo') !== null ? document.querySelector('#invoiceNo').textContent : ''
if ((cartTotal &&!cartTotal.includes('}}')) && (cartInvoiceNo && !cartInvoiceNo.includes('}}'))) {
setTagTotal(cartTotal)
setTagInvoiceNo(cartInvoiceNo)
}
let message = document.querySelector('#layout');
// INTERSECTION OBSERVER STUFF
const io = new IntersectionObserver(entries => {
if(entries[0].isIntersecting) {
console.log(entries);
}
}, {
threshold: [0]
});
// ELEMENTS TO OBSERVE
const blk1 = document.querySelector('#snipcart');
// START OBSERVING ELEMENTS
io.observe(blk1);
您应该更改代码,以便它检查是否有任何条目相交,而不仅仅是第一个条目,即更改
if(entries[0].isIntersecting)
{
console.log(entries);
}
到
您当前有
阈值:[0]
,这意味着
默认值为0(意味着只要有一个像素可见,就会运行回调)
如前所述
在观察之前,还应检查元素是否存在
if(element)
{
io.observe(element);
}
或者,如果您不知道元素何时会存在,您可以使用
MutationObserver
,如前所述。您可以尝试检查所有条目,而不仅仅是第一个条目?i、 e.将if(条目[0].isIntersecting){console.log(条目)}
更改为entries.forEach(条目=>{console.log(条目);}
谢谢,我现在得到intersecting:false,我相信它应该返回true,因为我的布局组件覆盖了整个窗口,并且`#snipcart'div在该窗口内,阈值为0是否正确?谢谢,这似乎可行,但是我想检查一个div,它在加载之前不存在,并且我发现错误无法执行'“IntersectionObserver”上的“observe”:参数1不是“Element”类型。如何通过首先检查元素是否存在来防止此错误?很高兴它可以工作,阈值0表示一旦它们开始相交。您可以只执行if(Element){io.observe(Element);}
或执行类似操作,然后等待加载元素。
if(element)
{
io.observe(element);
}