随鼠标向下滑动实现 视差滚动

1-min.gif

代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>视差滚动</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
<section>
    <h1>Good morning!</h1>
</section>
<section>
    <h1>Good afternoon!</h1>
</section>
<section>
    <h1>Good evening!</h1>
</section>
<section>
    <h1>How are you?</h1>
</section>
<section>
    <h1>Nice to meet you.</h1>
</section>
<section>
    <h1>It's nice to see you.</h1>
</section>
<section>
    <h1>Long time no see.</h1>
</section>
<section>
    <h1>How's it going?</h1>
</section>
<script src="gsap.min.js"></script>
<script src="ScrollTrigger.min.js"></script>
<script src="./main.js"></script>
</body>
</html>

代码scss

body{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
section{
  width: 100%;
  height: 100vh;
  display: flex;
  background-size: cover;
  background-position: center;
}

@for $i from 1 through 8 {
  section:nth-child(#{$i}){
     background-image: url('./imgs/image#{$i}.jpg');
  }
}

h1{
  font-size: 120px;
  margin: auto;
  color: rgb(207, 23, 23);
}

代码css

body {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

section {
  width: 100%;
  height: 100vh;
  display: flex;
  background-size: cover;
  background-position: center;
}

section:nth-child(1) {
  background-image: url("./imgs/image1.jpg");
}

section:nth-child(2) {
  background-image: url("./imgs/image2.jpg");
}

section:nth-child(3) {
  background-image: url("./imgs/image3.jpg");
}

section:nth-child(4) {
  background-image: url("./imgs/image4.jpg");
}

section:nth-child(5) {
  background-image: url("./imgs/image5.jpg");
}

section:nth-child(6) {
  background-image: url("./imgs/image6.jpg");
}

section:nth-child(7) {
  background-image: url("./imgs/image7.jpg");
}

section:nth-child(8) {
  background-image: url("./imgs/image8.jpg");
}

h1 {
  font-size: 120px;
  margin: auto;
  color: rgb(207, 23, 23);
}

/*# sourceMappingURL=style.css.map */

代码js

const sections = document.querySelectorAll('section');
gsap.registerPlugin(ScrollTrigger); // 注册插件
sections.forEach(section => {
    gsap.fromTo(section,
        {backgroundPositionY: `-${window.innerHeight / 2}px`},
        {
            backgroundPositionY: `${window.innerHeight / 2}px`,
            ease: 'none',
            scrollTrigger: {
                trigger: section,
                scrub: true
            }
        });

});

js代码知识点

  • document.querySelectorAll('section'):用于获取页面上所有的 <section> 元素。
  • gsap.registerPlugin(ScrollTrigger):注册 ScrollTrigger 插件,以便在后续代码中使用其功能。
  • 在循环中,通过 gsap.fromTo 方法对每个 <section> 元素进行动画设置。

    • 定义了起始的背景位置 backgroundPositionY
    • 定义了结束的背景位置 backgroundPositionY
    • ease: 'none' 表示使用线性的缓动效果。
    • scrollTrigger 对象中设置触发元素为当前循环的 <section> 元素,以及 scrub: true 表示动画跟随滚动实时进行。
Last modification:August 13, 2024
如果觉得我的文章对你有用,请随意赞赏