背景
经常看到一些首页的过渡效果不错,闲来无事,实现个基本效果
直接上代码
<body>
<div id="1" class="block build-in-scale-up"><h1>Hello1</h1></div>
<div id="2" class="block build-in-scale-up"><h1>Hello2</h1></div>
<div id="3" class="block build-in-scale-up"><h1>Hello3</h1></div>
<div id="4" class="block build-in-scale-up"><h1>Hello4</h1></div>
<div id="5" class="block build-in-scale-up"><h1>Hello5</h1></div>
</body>
<script>
function addAni() {
let panels = document.getElementsByTagName("div");
for (let i = 0; i < panels.length; i++) {
let p = panels[i];
let id = p.getAttribute("id");
let scrollTop = document.body.scrollTop;
let scrollHeight = document.body.clientHeight;
let offsetTop = p.offsetTop;
let clientHeight = document.body.clientHeight;
console.log(
id,
scrollHeight,
"scrollTop",
scrollTop + clientHeight - 100,
"panel offsetTop",
offsetTop
);
if (scrollTop + clientHeight - 100 > offsetTop) {
p.classList.add("build-in-animate");
} else {
p.classList.remove("build-in-animate");
}
}
}
window.addEventListener("scroll", addAni);
addAni();
</script>
<style>
.block {
height: 300px;
background-color: bisque;
margin: 5px;
}
.build-in-scale-up.build-in-animate {
opacity: 1;
transform: scale(1) translateY(0);
}
.build-in-scale-up {
/* opacity: 0; */
transition: opacity 0.7s cubic-bezier(0.16, 1, 0.3, 1),transform 0.7s cubic-bezier(0.16, 1, 0.3, 1);
transform: scale(0.96) translateY(24px);
}
</style>
效果如下:
滚动到元素刚出现时,呈现一个放大的效果。
图1:刚出现的效果
图2:继续滚动Hello3面板会放大到最终位置
总结
- 适当的过渡效果让页面没那么生硬
- 当滚动到元素出现时,添加样式。实现原理与滚动加载差不多。不过也有点区别(scrollTop + clientHeight - 100 > offsetTop)
- 添加样式后会展现过渡效果