我正在使用 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 .....
我的代码有什么问题?为什么索引总是0,但通过获得的索引访问会导致正确的元素?
编辑