Web production note

 【更新日 :

【脱Jquery】JavaScriptでシンプルなパララックスを実装する

Category:
JavaScript

Vanilla JSでシンプルなパララックスを実装したサンプルです。

※なるべく低負荷になるよう Intersection Observer を組み合わせてパララックスを実装したサンプルも公開しました。

動作サンプル

表示エリアからはみ出している量だけ画像が動きます。
スクロール中に要素がエリアから飛び出さないように動く量はウィンドウの高さに応じて算出しています。

codepen

See the Pen Simple Parallax Vanilla JS by web_nak (@web_walking_nak) on CodePen.

HTML

表示エリア .js-parallax-elm-box の中に、動かす要素 .js-parallax-elm を内包してください。
上記は画像を格納していますが、何が入っていても動きます。

CSS

表示エリアからはみ出している要素を隠すため、最低限overflow: hidden;を設定してください。
※表示エリアのheightは実装するデザインに応じて適宜設定してください。

.js-parallax-elm-box {
  overflow: hidden;
}
.js-parallax-elm-box img {
  display: block;
}

JavaScript

対象class名を変更したい場合は、targetClass「表示エリア class」と、childClass「動かす要素 class」を編集してください。

//Simple Parallax Vanilla JS
function parallax() {
  'use strict';

  //class設定
  //表示エリア class
  const targetClass = '.js-parallax-elm-box';
  //動かす要素 class
  const childClass = '.js-parallax-elm';

  //表示エリア取得
  const targets = Array.prototype.slice.call(document.querySelectorAll(targetClass),0);
  //表示エリアが存在するかチェック
  if(targets.length === 0) {
    return false;
  }

  //ウィンドウの高さ取得
  let winH = window.innerHeight;

  //パララックス関数呼び出し
  parallaxFunk();
  window.addEventListener('resize', function(){
    winH = window.innerHeight;
    requestAnimationFrame(parallaxFunk);
  });
  window.addEventListener('scroll', function(){
    requestAnimationFrame(parallaxFunk);
  });

  //パララックス関数
  function parallaxFunk() {
    //スクロール量(ウィンドウの上端)取得
    const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
    //スクロール量(ウィンドウの下端)取得
    const scrollBottom = scrollTop + winH;

    //表示エリアごとの設定
    targets.forEach(function(target){
      //表示エリアの位置取得
      const targetPosi =  target.getBoundingClientRect().top + scrollTop;
      //表示エリアの高さ取得
      const targetHeight =  target.clientHeight;
      //表示領域の取得
      const targetShowPosi = targetPosi - winH;
      //表示エリアの終了位置取得
      const targetEndPosi = targetPosi + targetHeight;

      //表示エリアがモニター画面に入った場合の処理
      if(scrollTop > targetShowPosi && scrollTop < targetEndPosi) {
        //動かす要素を取得
        const child = target.querySelector(childClass);
        //動かす要素が存在するかチェック
        if(!child) {
          return false;
        }
        //動かす要素の高さ取得
        const childHeight = child.clientHeight;
        //パララックス スクロールできる最大量を取得
        const maxVal = childHeight - targetHeight;
        //ウィンドウの高さに対するスクロール量を取得(小数点第2以下は四捨五入)
        const setVal = ((scrollBottom - targetPosi) * (maxVal/(winH+targetHeight))).toFixed(1);
        //スクロール値を設定
        child.style.transform = 'translate3d(0,'+(-setVal)+'px,0)';
      }
    });
  }
}

関数の呼び出し

任意の場所で以下を実行し関数を呼び出してください。

//パララックス呼び出し
parallax();

関連リンク

参考リンク