【问题标题】:Why is Intersection Observer adding class to all observed elements upon intersection of first element?为什么 Intersection Observer 在第一个元素相交时向所有观察到的元素添加类?
【发布时间】:2020-04-05 17:24:53
【问题描述】:

请原谅我的无知,因为我正在学习。我正在努力让 divs 和 .entry 类在与 Intersection Observer 相交时通过向它们添加 .entry-animation 类来制作动画。

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

演示如下:

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));

【问题讨论】:

    标签: javascript html css animation intersection-observer


    【解决方案1】:

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

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

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

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

    Working Demo

    【讨论】:

    • 啊当然。感谢您的所有帮助,并保持安全!
    • 很高兴它对您有所帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多