parallax


parallax
  • をスクロールすると、1番目の画像が2番目の画像で上書きされます.
  • 最初のイメージでは、イメージの実行速度が異なります.
  • ちくじず
  • スクロール時にイベントを開始します.
  • スクロール時にラベル、位置、速度を追加できるパラメータを使用して、
  • 関数を作成します.
    -スクロール時に位置値を求め、位置*速度で画像の変換値を変更します.
    (最初の画像が上書きされた場合、cssz-index:-1;追加する必要があります)
  • html
    <header>
        <div class="intro-text">
          <h1>Comfort</h1>
          <h3>Your dearm inerior design</h3>
        </div>
        <img src="img/toy.jpg" alt="" class="toy">
        <img src="img/toy2.jpg" alt="" class="big-toy">
        <img src="img/toy3.jpg" alt="" class="small-toy">
      </header>
      <section>parallax</section>
    css
    * {
      margin:0;
      padding:0;
      box-sizing:border-box;
    }
    header {
      min-height:100vh;
      background:linear-gradient(240deg, #834d4d, #503d3d);
      position:relative;
      color:#fff;
      font-family:sans-serif;
      z-index:-1;
    }
    
    .intro-text {
      position:absolute;
      top:50%;
      left:20%;
      transform:translate(-20%, -50%);
      z-index:2;
    }
    .intro-text h1 {
      font-size:60px;
      margin-bottom:10px;
    }
    .intro-text h3 {
      font-size:35px;
    }
    
    .toy {
      height:700px;
      position:absolute;
      top:90%;
      right:10%;
      transform:translate(-10%, -90%);
    }
    
    .big-toy {
      height:200px;
      position:absolute;
      top:10%;
      right:40%;
    }
    
    .small-toy {
      height:100px;
      position:absolute;
      top:30%;
      right:10%;
    }
    
    section {
      min-height:100vh;
      color:#934d4d;
      display:flex;
      justify-content: center;
      align-items: center;
      font-size:50px;
      font-family:sans-serif;
      background-color:lightseagreen
    }
    javascript
    function parallax( element, distance, speed ){
      const item = document.querySelector(element);
      item.style.transform = `translateY(${distance *speed}px)`;
    }
    
    window.addEventListener('scroll', function(){
      parallax('header', window.scrollY, 1);
      parallax('.big-toy', window.scrollY, 0.5);
      parallax('.small-toy', window.scrollY, 0.1);
    });