如何用js完成滚动视差的效果?

How to use js to complete the effect of scrolling parallax?

我是编程初学者,现在想完成一个效果! 当鼠标向下滚动时,屏幕上的元素会跟着位置偏移,当鼠标再次向上滚动时,元素也会偏移到原来的位置。 但是,当鼠标停止时,不能连续移动位置来实现滚动视差效果。

但是目前我想实现的效果是给一个固定的偏移位置 duck.style.transform = 'translateY(100px)'; 这将导致元素在鼠标不滚动时移动。我该如何解决这个问题? ?

期望的效果类似于下面的 URL 示例 https://codepen.io/hong-wei/pen/rNGbgKQ?editors=1010

let duck = document.querySelector(".duck");
let cloud1 = document.querySelector(".cloud1");
let cloud2 = document.querySelector(".cloud2");
let cloud3 = document.querySelector(".cloud3");

$(document).on("scroll", function() {
  if (window.pageYOffset > 0) {
    duck.style.transform = "translateY(100px)";
    cloud1.style.transform = "translateY(120px)";
    cloud2.style.transform = "translateY(80px)";
    cloud3.style.transform = "translateY(60px)";

    // duck.style.transition = '2s';
  } else {
    duck.style.transform = "translateY(-100px)";
    cloud1.style.transform = "translateY(-120px)";
    cloud2.style.transform = "translateY(-80px)";
    cloud3.style.transform = "translateY(-60px)";
  }
});
.wrap {
  position: relative;
  background-color: #222;
  height: 1000px;
}

.wrap .duck {
  width: 300px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  transition: 1s;
}

.wrap .cloud1 {
  position: absolute;
  top: 60px;
  width: 360px;
  left: 30px;
  transition: 2s;
}

.wrap .cloud2 {
  position: absolute;
  top: 200px;
  right: 100px;
  width: 160px;
  transition: 2s;
}

.wrap .cloud3 {
  position: absolute;
  top: 320px;
  width: 560px;
  transition: 2s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
  <img class="duck" src="https://upload.cc/i1/2022/02/15/UB1kXd.png
" alt="">
  <img class="cloud1" src="https://upload.cc/i1/2022/02/19/7P4hcu.png
" alt="">
  <img class="cloud2" src="https://upload.cc/i1/2022/02/19/7P4hcu.png
" alt="">
  <img class="cloud3" src="https://upload.cc/i1/2022/02/19/7P4hcu.png
" alt="">
</div>

希望这能解决您的问题。

let duck = document.querySelector(".duck");
let cloud1 = document.querySelector(".cloud1");
let cloud2 = document.querySelector(".cloud2");
let cloud3 = document.querySelector(".cloud3");

window.addEventListener("scroll", function() {
    let rate = window.scrollY * 1;
    let rateCloudsPositive = window.scrollY * 3;
    let rateCloudsNegative = window.scrollY * -3;
    duck.style.transform = `translateY(${rate}px)`;
    cloud1.style.transform = `translateY(${rateCloudsPositive}px)`;
    cloud2.style.transform = `translateY(${rate}px)`;
    cloud3.style.transform = `translateY(${rate}px)`;

    // duck.style.transition = '2s';
    duck.style.transform = `translateY(${rateCloudsNegative}px)`;
    cloud1.style.transform = `translateY(${rateCloudsNegative}px)`;
    cloud2.style.transform = `translateY(${rateCloudsNegative}px)`;
    cloud3.style.transform = `translateY(${rateCloudsNegative}px)`;
});