javascript - 使用 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);
解决方案
您应该更改您的代码,以便它检查是否有任何条目相交,而不仅仅是第一个,即更改
if(entries[0].isIntersecting)
{
console.log(entries);
}
至
entries.forEach(entry =>
{
console.log(entry);
});
你目前有threshold: [0]
什么意思
默认值为 0(意味着只要一个像素可见,就会运行回调)。
如此处所述。
您还应该在观察之前检查您的元素是否存在。
if(element)
{
io.observe(element);
}
或者如果您不知道该元素何时存在,您可以使用这里MutationObserver
解释的。
推荐阅读
- matlab - 计算自相关函数集,然后求和
- python - 如何在 folium 地图的工具提示上显示 JSON 数据?
- c# - RedirectStandardOutput 显示进程关闭后的结果 C#(不逐行显示输出)
- c# - 用多个表填充列表对象
- javascript - AWS S3:如何检索存储桶活动?
- java - 打开 onClick 按钮一个带有画布绘图的新活动
- github - 允许管理员在不受 github 保护的分支上的 pull request 批准的情况下合并
- php - 如何从 3 位 php 变量中打印单独的数字?
- r - 在 R 中手动预测 ARIMA
- javascript - 如何在 React 中基于动态键渲染元素?