bilibili (b 站) 小型火箭页面向上划动的动画效果实现
最编程
2024-03-26 09:50:35
...
Javascript代码实现
// 获取当前视口的大小
var viewHeight = document.documentElement.clientHeight/4;
//小火箭添加单击事件
document.querySelector(".back-to-top").addEventListener("click", () => {
//小火箭被单击,回到顶部
// document.documentElement.scrollTop = 0;
//当然,也可以慢慢回到顶部
slowToTop();
})
//当然,这里使用节流会更好
window.onscroll = function () {
if (document.documentElement.scrollTop >= viewHeight) {
//显示小火箭元素
document.querySelector(".back-to-top").style.display = "block";
} else {
//隐藏小火箭
document.querySelector(".back-to-top").style.display = "none";
}
}
window.onresize = function () {
viewHeight = document.documentElement.clientHeight;
}
/* 缓慢回到顶部 */
function slowToTop() {
setTimeout(() => {
let value = document.documentElement.scrollTop;
if(value<=0){
document.documentElement.scrollTop = 0;
}else{
document.documentElement.scrollTop -= 40;
slowToTop();
}
}, 1000/50);
}
CSS实现
.back-to-top {
background-image: url("../picture/rocket_top.png");
position: fixed;
right: 20px;
bottom: 20px;
text-align: center;
width: 150px;
height: 175px;
border-radius: 50%;
display: none;
z-index:4;
}
.back-to-top:hover {
animation: fly 0.4s steps(1) infinite;
background-image: url("../picture/rocket_frame.png");
}
@keyframes fly {
0% {
background-position-x: 0;
}
25% {
background-position-x: -150px;
}
50% {
background-position-x: -300px;
}
75% {
background-position-x: -450px;
}
to {
background-position-x: -600px;
}
}
html引用
<div class="back-to-top"></div>