0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Intersection Observer API(監視対象を増やす)

Last updated at Posted at 2022-11-13

・queryselectorAllを使い全部を取得する。
・forEachを使い全部やる。

ちなみに、、、、
entriesには監視している全ての要素が入ってくるわけではない。
entriesは複数の要素を持つ配列で、監視開始時点では全てのtargetが、交差した時では交差したtargetだけが要素として入ってくる。

const targets = document.querySelectorAll('img');

  function callback(entries, obs) {
    console.log(entries);

    if (!entries[0].isIntersecting) {
      return;
    }

    entries[0].target.classList.add('appear');
    obs.unobserve(entries[0].target);
  }

  const options = {
    threshold: 0.2,
  };

  const observer = new IntersectionObserver(callback, options);

  targets.forEach(target => {
    observer.observe(target);
  });

上のままだと全ての要素に対して影響を与えていない。

変更すると、、、

  const targets = document.querySelectorAll('img');

  function callback(entries, obs) {
    console.log(entries);

    entries.forEach(entry => {
      if (!entry.isIntersecting) {
        return;
      }
  
      entry.target.classList.add('appear');
      obs.unobserve(entry.target);
    });
  }

  const options = {
    threshold: 0.2,
  };

  const observer = new IntersectionObserver(callback, options);

  targets.forEach(target => {
    observer.observe(target);
  });

これで全てがふわっとくるようになる。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?