Technicalarticles

用10行JavaScript代码制作一款漂亮的视差效果
作者:赵刘伟 时间:2020-10-26 浏览量:

英文 | https://www.ibrahima-ndaw.com/blog/parallax-effect-with-10-lines-of-javascript/

翻译 | web前端开发(web_qdkf)

在本文中,我们将使用HTML,CSS和仅10行JavaScript代码来制作一个漂亮的视差效果。

首先,我们来看一下最终完成的视差效果的动画图:


02-1.gif

接着,我们开始HTML的编写。在HTML中,我们首先将其他元素包裹在main标记中,以下是HTML代码。

HTML


<main>  <header>    <div>      <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>

然后,我们使用两个标签制作视差效果。第一个标记header包含页面加载时显示的元素,第二个标记section将在滚动时触发以启动效果。

CSS

在CSS这部分里,我们需要先进行一些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;}

接着,我们用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;}

在这里,我们为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);  }}

最后,虽然不是最不重要的一点,但我们为元素入口制作了一些动画。section的反弹效果header的褪色效果该类animate-me将section通过JavaScript添加到后面。

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)})
如你在这里看到的,我们收听scroll事件以开始效果。
然后,我们将通过Y轴(垂直)distance的数量分配给常量scroll。然后从DOM中选择所需的元素并访问该transform属性。
这样,我们现在就可以使用该translateY值动态地将赋值给translateY。该值header与其子元素之间有所不同container,只是效果更平滑。然后,通过添加弹跳效果标题的animate-me类来完成所有操作section。
这就是这个效果的全部内容,最终效果如下:

02-2.gif

返回列表

想和你做个朋友

DO U LIKE?