用 10 行 JavaScript 实现视差效果

2025-05-27

用 10 行 JavaScript 实现视差效果

最初发布在我的博客上


在这篇文章中,我们将使用 HTML、CSS 和仅 10 行 JavaScript 制作出漂亮的视差效果。

您可以在这里实时查看

HTML

正如您所见,我们首先将元素包装在main标签中。



    <main>
      <header>
        <div class="container">
          <i class="fas fa-5x fa-laugh"></i>
          <h3>Welcome</h3>
          <p>Scroll to see how cool i am!</p>
        </div>
      </header>

      <section>
        <h3>Cool like you</h3>
      </section>
    </main>


Enter fullscreen mode Exit fullscreen mode

然后,我们使用两个标签来实现视差效果。第一个标签header保存页面加载时显示的元素,第二个标签section将在页面滚动时触发,以启动视差效果。

CSS

像往常一样,我们首先进行一些重置并导入所需的字体。



@import url("https://fonts.googleapis.com/css?family=Courgette:400,700&display=swap");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: linear-gradient(135deg, #0056a7, #165fa3, #477aaa);
  font-family: "Courgette", cursive;
}

header {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  position: relative;
  height: 100vh;
  color: #eee;
  z-index: -1;
  text-align: center;
  animation: fadeIn 1.5s ease-in-out;
}


Enter fullscreen mode Exit fullscreen mode

然后,我们使用它position:relative来控制header标签的位置,并且当效果开始时,该属性z-index:-1将把header标签放在元素后面section



section {
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
  height: 100vh;
  font-size: 5rem;
  background: #fcdb6d;
  color: #0056a7;
}


Enter fullscreen mode Exit fullscreen mode

在这里,我们对section选择器使用相反的方法,通过分配z-index属性来在我们开始滚动时将标签1放置section在上方。header



.animate-me {
  animation: bounceIn 3s ease-in-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes bounceIn {
  0% {
    transform: scale(0.1);
    opacity: 0;
  }
  60% {
    transform: scale(1.2);
    opacity: 1;
  }
  100% {
    transform: scale(1);
  }
}


Enter fullscreen mode Exit fullscreen mode

最后,同样重要的是,我们为元素的入口制作一些动画。包括 的弹跳效果section和 的淡入淡出效果。之后,我们将通过 JavaScript将headerclassanimate-me添加到 中。section

JavaScript

我们最终将使用 JavaScript 来实现魔法,以便在滚动时产生视差效果。



window.addEventListener("scroll", function() {
  const distance = window.scrollY;
  document.querySelector("header").style.transform = `translateY(${distance *
    1}px)`;
  document.querySelector(
    ".container"
  ).style.transform = `translateY(${distance * 0.3}px)`;
  setTimeout(() => {
    document.querySelector("section h3").classList.add("animate-me");
  }, 400);
});


Enter fullscreen mode Exit fullscreen mode

正如您在此处所见,我们监听事件scroll以启动效果。然后,我们将沿 Y 轴(垂直方向)的量

赋给常量。并从 DOM 中选择所需元素并访问属性。 这样,我们现在可以使用值动态地为 赋值。及其子元素之间的值有所不同,以使效果更平滑。最后,我们完成所有操作,为标题添加类来实现弹跳效果。distancescrolltransform
translateYtranslateYheadercontaineranimate-mesection

就这样吧,伙计们!

您可以在这里实时查看

全屏滑块

文章来源:https://dev.to/ibrahima92/make-a-parallax-effect-with-10-lines-of-javascript-3hia
PREV
2025 年最佳免费开源图标和图标包 icons-font-customization 图标集合:
NEXT
附加 VS 附加子项