【发布时间】:2019-12-08 16:37:39
【问题描述】:
我正在使用 IntersectionObserver API。
输入特定部分时,background-color 会更改。
为了处理这个问题,我必须在此处获取IntersectionObserverEntry 数组中输入条目的索引,称为entries。
我使用forEach 方法获取条目的索引,但奇怪的是它总是将索引设置为0。但是当我通过获取的索引访问条目时,它运行良好。
const intersectionObserver = new IntersectionObserver(entries => {
entries.forEach((entry,index) => {
if(entry.isIntersecting) {
console.log('Intersecting',index);
entry.target.className = entry.target.className.replace('hidden','fadeIn');
changeBackgroundColor(entry.target.dataset.color);
changeLogoColor(entry.target.dataset.theme);
} else {
console.log('Leave',index);
entry.target.className = entry.target.className.replace('fadeIn','hidden');
}
});
});
const fadeInElemes = document.querySelectorAll('.hidden');
fadeInElemes.forEach((fadeInElem) => intersectionObserver.observe(fadeInElem));
结果如下...
相交0
离开 0
留下0.....
我的代码有什么问题?为什么 index 总是为 0,但通过获取的 index 访问会得到正确的元素?
编辑
【问题讨论】:
-
恕我直言,您的问题不是
indexOf()行为,请尝试记录数组entries -
@MosèRaguzzini 我为此进行了编辑。
-
Ok indexOf 失败,因为对象比较浅,只返回找到的第一个项目
-
不,尝试迭代并记录 foreach 第二个参数(索引),您可能不需要 indexOf()
-
因为 IntersectionObserver 回调中的条目数组仅包含一项,并且fadeInElemes 正在设置观察者 N 次?所以每个 Intersecting 0, Leave 0, Leave 0 都被fadeInElems foreach observe call调用
标签: javascript arrays intersection-observer