IntersactionObserver() 仅观察一行的第一个元素,而不是所有元素

我正在尝试 IntersectionObserver(),它的行为很奇怪:我使用一个非常简单的布局,在同一个 div 中只有 8 个图像与 Flexbox,使用换行,所以基本上这 8 个图像将自己定位在不同的行中,根据视口的大小。我首先将过滤器类(添加模糊过滤器)应用于每个元素,然后在它们显示在屏幕上时将其删除:


HTML:


<div class="flex--cont">

            <div class="box box-2">

                <img src="img/1.jpg" alt="" class="img img-1">

            </div>

            <div class="box box-1">

                <img src="img/2.jpg" alt="" class="img img-2">

            </div>

            <div class="box box-3">

                <img src="img/3.jpg" alt="" class="img img-3">

            </div>

            <div class="box box-4">

                <img src="img/4.jpg" alt="" class="img img-4">

            </div>

            <div class="box box-5">

                <img src="img/5.jpg" alt="" class="img img-5">

            </div>

            <div class="box box-6">

                <img src="img/6.jpg" alt="" class="img img-6">

            </div>

            <div class="box box-7">

                <img src="img/7.jpg" alt="" class="img img-7">

            </div>

            <div class="box box-8">

                <img src="img/8.jpg" alt="" class="img img-8">

            </div>

        </div>

脚本语言


const allImage = Array.from(document.querySelectorAll(".img"));

allImage.forEach((img) => img.classList.add("filter"));


const removeFilter = function (entries, observer) {

  const [entry] = entries;

  const image = entry.target;

  image.classList.remove("filter");

};


const ImageObserver = new IntersectionObserver(removeFilter, {

  root: null,

  threshold: 0.15,

});


allImage.forEach((img) => ImageObserver.observe(img));

问题是观察者实际上只观察每行的第一个元素,所以如果我有 2 行,它只会获得第 1 和第 5 个图像,如果我有 3 行,它会获得第 1、第 4 和第 7 个图像等等。我确实已将其应用于所有图像。它为什么要这么做?感谢您的回答!


MMMHUHU
浏览 77回答 1
1回答

冉冉说

只有第一个发生了变化,因为这就是您通过仅解构第一个数组元素来更改颜色函数的目标:const [entry] = entries;但是,InteractionObserver回调不是针对每个条目调用的,而是针对同时触发的所有条目调用的;因此该entries数组包含所有被观察的项目,您需要isIntersecting像这样检查属性:const changeColor = function(entries) {&nbsp; entries.forEach(entry => {&nbsp; &nbsp; if(entry.isIntersecting) {&nbsp; &nbsp; &nbsp; entry.target.style.background = 'blue';&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; entry.target.style.background = 'red';&nbsp; &nbsp; }&nbsp; })}来自 MDN 文档let callback = (entries, observer) => {&nbsp; entries.forEach(entry => {&nbsp; &nbsp; // Each entry describes an intersection change for one observed&nbsp; &nbsp; // target element:&nbsp; &nbsp; //&nbsp; &nbsp;entry.boundingClientRect&nbsp; &nbsp; //&nbsp; &nbsp;entry.intersectionRatio&nbsp; &nbsp; //&nbsp; &nbsp;entry.intersectionRect&nbsp; &nbsp; //&nbsp; &nbsp;entry.isIntersecting&nbsp; &nbsp; //&nbsp; &nbsp;entry.rootBounds&nbsp; &nbsp; //&nbsp; &nbsp;entry.target&nbsp; &nbsp; //&nbsp; &nbsp;entry.time&nbsp; });};
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript