首页 > 解决方案 > 使用 intersectionObserver 检查元素是否可见

问题描述

在我的 next.js 组件布局中,我试图检查包含 div #snipcart 的模态窗口何时在窗口中可见。

我正在尝试使用 IntersectionObserver 来检查这一点,但我没有得到输出?

如何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);

标签: javascriptreactjsnext.js

解决方案


您应该更改您的代码,以便它检查是否有任何条目相交,而不仅仅是第一个,即更改

if(entries[0].isIntersecting) 
{ 
    console.log(entries);
}

entries.forEach(entry => 
{ 
    console.log(entry);
});

你目前有threshold: [0]什么意思

默认值为 0(意味着只要一个像素可见,就会运行回调)。

如此所述。


您还应该在观察之前检查您的元素是否存在。

if(element)
{
    io.observe(element);
}

或者如果您不知道该元素何时存在,您可以使用这里MutationObserver解释的。


推荐阅读