用 10 行 JavaScript 实现视差效果
最初发布在我的博客上
在这篇文章中,我们将使用 HTML、CSS 和仅 10 行 JavaScript 制作出漂亮的视差效果。
您可以在这里实时查看
- 1. HTML
- 2. CSS
- 3. 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>
然后,我们使用两个标签来实现视差效果。第一个标签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;
}
然后,我们使用它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
和 的淡入淡出效果。之后,我们将通过 JavaScript将header
classanimate-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);
});
正如您在此处所见,我们监听事件scroll
以启动效果。然后,我们将沿 Y 轴(垂直方向)的量
赋给常量。并从 DOM 中选择所需元素并访问属性。 这样,我们现在可以使用值动态地为 赋值。及其子元素之间的值有所不同,以使效果更平滑。最后,我们完成所有操作,为标题添加类来实现弹跳效果。distance
scroll
transform
translateY
translateY
header
container
animate-me
section
就这样吧,伙计们!
您可以在这里实时查看