繁体   English   中英

为什么 Intersection Observer 在第一个元素相交时将 class 添加到所有观察到的元素?

[英]Why is Intersection Observer adding class to all observed elements upon intersection of first element?

请原谅我的无知,因为我正在学习。 我正在使用 .entry 的.entry获取div ,以便通过向它们添加 .entry .entry-animation的 class 来在与 Intersection Observer 相交时进行动画处理。

我以前从未选择过所有元素并制作动画。 在第一个交叉点上,所有元素同时进行动画处理。 我究竟做错了什么?

这是演示:

JSFiddle

这是 HTML

  <div id="content-container">
    <div class="content">

      <div class="entry">
        <h2>
          Title of Post 1
        </h2>
        <p>
          Some content here on each entry
        </p>
      </div>
      <div class="entry">
        <h2>
          Title of Post 2
        </h2>
        <p>
          Some content here on each entry
        </p>
      </div>
      <div class="entry">
        <h2>
          Title of Post 3
        </h2>
        <p>
          Some content here on each entry
        </p>
      </div>
      <div class="entry">
        <h2>
          Title of Post 4
        </h2>
        <p>
          Some content here on each entry
        </p>
      </div>
      <div class="entry">
        <h2>
          Title of Post 5
        </h2>
        <p>
          Some content here on each entry
        </p>
      </div>
      <div class="entry"></div>
    </div>
  </div>

这是 CSS:

body {
  background: #FFF;

}

.entry {
  background: #f6f6f6;
  text-align: center;
  padding: 5%;
  margin: 5%;
  border: 1px solid #ccc;
  border-radius: 15px;
  box-shadow: 0 4px 5px #cecece;
}


.entry-animation {
    animation: 2s fadeIn-1;
    animation-fill-mode: both;
}

@keyframes fadeIn-1 {
    0% {
        transform: translateY(20%);
        opacity: 0;
}
    100%{
        transform: translateY(0);
        opacity:1;
    }
}

这是JS:

const options = {
  threshold: 0.4,
};

const blogs = document.querySelectorAll('.entry');

const observer = new IntersectionObserver(function(entries, observer) {

  entries.forEach((entry) => {

    if (!entry.isIntersecting) {
      return;
    }
    blogs.forEach(blog => blog.classList.add('entry-animation'));


  },options);
});

blogs.forEach(blog => observer.observe(blog));

您可以通过替换轻松解决此问题:

blogs.forEach(blog => blog.classList.add('entry-animation'));

entry.target.classList.add('entry-animation')

entries.forEach()循环内。 这里的问题基本上是我们只需要将 animation class 仅添加到使用entry.target视图中的元素中,而不是一次将它们添加到所有元素中。

工作演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM