LoginSignup
1
1

More than 3 years have passed since last update.

複数の要素をスクロール検知してアニメーションを行う

Last updated at Posted at 2020-08-01

よくポートフォリオサイトなどで見かけるスクロールすると画像がフェードインしてくる感じのものが作れます。

IntersectionObserver

".made-item"が付いている要素を取得して、それぞれの要素が特定のスクロールポイントに来たときにclassを付与、消去するプログラムです。

function() {
      const items = document.querySelectorAll('.made-item')
      const cb = function(entries, observer) {
        entries.forEach(entry => {
          if (entry.isIntersecting) {
            console.log('はいったときの処理');
            console.log(entry.target);
            entry.target.classList.add('inview')
          } else {
            console.log('でたときの処理');
            entry.target.classList.remove('inview')
          }
        })
      }
      const options = {
        root: null,
         //交差する要素を設定できる 変更することはあまりない
        rootMargin: '0px 0px -300px 0px',
        //交差点の場所をmarginのように指定できる
        threshold: 0
        // 初期値は0 0は交差点に入ってくる要素の下の部分 1は上の部分でcbが呼ばれる
        // 配列で[0, 0.5, 1とすると要素の上、真ん中、下でそれぞれcbが呼ばれる
      }
      const io = new IntersectionObserver(cb, options)
      items.forEach(item => {
        io.observe(item)
     // io.observe(item2)
     // io.observe(item3)
     // ioの中に↑こんな感じで要素を複数入れられます
      })
    }
  • querySelictorAllで複数のclassを指定
  • forEachでそれを回して変数io(newしたIntersectionObserver)に代入
  • 上記の要素がcbの引数entriesに入るので入ったとき、出たときの処理を記入
  • 交差点の要素はentry.targetで確認できる

scrollY

let scroll = 0
function() {
    scroll = window.scrollY
    console.log(scroll);
    }
  • スクロールで上端からのピクセル数を検知
1
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
1
1