0
1

More than 1 year has passed since last update.

Intersection Observer API(ターゲットが交差する%)

Last updated at Posted at 2022-11-13

Intersection Observer API

ある要素がスクロールして、特定の領域に入ったら、どれだけ交差しているか調べる。
領域:root
要素:target
割合:Intersection Ratio

ex)imgが一つある。それが画面に入ってくる。

 const target = document.querySelector('img');

  function callback() {
    console.log('fired!');
  }

  const observer = new IntersectionObserver(callback);

  observer.observe(target);

・observer()は()を監視して。
・new IntersectionObserver()は、IntersectionObserverは()の仕事をする。
・これらの処理は監視が始まった時、0%の時(最初と最後)の計三回ある。
→じゃあ%を指定したい時はどうするの?→threshold

%の指定

const target = document.querySelector('img');

  function callback() {
    console.log('fired!');
  }

  const options = {
    threshold: [0.2, 0.8],
  };

  const observer = new IntersectionObserver(callback, options);

  observer.observe(target);

・第二引数を渡してあげればよい。
・20%と80%のの時が追加される。

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