【问题标题】:check whether element is visible using intersectionObserver使用 intersectionObserver 检查元素是否可见
【发布时间】:2021-02-19 05:15:19
【问题描述】:

在我的 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);

【问题讨论】:

  • 您可以尝试检查所有条目而不是只检查第一个条目吗?即将if(entries[0].isIntersecting) { console.log(entries) }更改为entries.forEach(entry => { console.log(entry); }
  • 谢谢,我现在得到了相交:false,我相信它应该返回 true,因为我的布局组件覆盖了整个窗口并且 `#snipcart' div 在此窗口内,阈值为 0 正确?
  • 谢谢,这似乎可行,但是我想检查一个在加载之前不存在的 div,并且我收到错误 Failed to execute 'observe' on 'IntersectionObserver': 参数 1不是“元素”类型。如何通过先检查元素是否存在来防止此错误?
  • 很高兴它有效,阈值 0 意味着一旦它们开始相交。你可以只做if(element) { io.observe(element); } 或者你可以做类似this 的事情,然后等待元素加载。

标签: javascript reactjs next.js


【解决方案1】:

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

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

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

您目前拥有threshold: [0],这意味着

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

正如here 解释的那样。


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

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

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

【讨论】:

    猜你喜欢
    • 2020-12-10
    • 2011-02-08
    • 2023-03-04
    • 2017-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-08
    • 2013-11-09
    • 2017-04-25
    相关资源
    最近更新 更多