首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IntersactionObserver()只观察一行的第一个元素,而不是所有元素

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

Stack Overflow用户
提问于 2020-11-26 05:15:02
回答 1查看 237关注 0票数 0

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

HTML:

代码语言:javascript
复制
<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>

JAVASCRIPT

代码语言:javascript
复制
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));

问题是观察者实际上只观察到每行的第一个元素,所以如果我有两行,它只会得到第一和第五张图像,如果我有三行,它就会得到第一张,第四张和第七张图像,依此类推。我已经把它应用到了所有的图像上。它为什么要这么做?感谢您的回答!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-26 08:57:16

只有第一个是改变的,因为那是你在改变颜色功能中的全部目标。'entries‘数组包含所有要观察的项,您需要检查'isIntersecting’属性,如下所示:

代码语言:javascript
复制
const changeColor = function(entries) {
  entries.forEach(entry => {
    if(entry.isIntersecting) {
      entry.target.style.background = 'blue';
    } else {
      entry.target.style.background = 'red';
    }
  })
}

从MDN文档

代码语言:javascript
复制
let callback = (entries, observer) => {
  entries.forEach(entry => {
    // Each entry describes an intersection change for one observed
    // target element:
    //   entry.boundingClientRect
    //   entry.intersectionRatio
    //   entry.intersectionRect
    //   entry.isIntersecting
    //   entry.rootBounds
    //   entry.target
    //   entry.time
  });
};
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65012773

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档