突发觉得这种bilibili小火箭很有意思,想看看怎么实现的,发现是精灵图来实现的已经实现了滚动到顶部~css中animation的steps分步动画效果素材代码基础动画效果1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>bilibili小火箭</title> <style> * { margin: 0; padding: 0; } .rock { position: fixed; right: 0; bottom: 0; width: 150px; height: 174px; background-image: url("img/rocket_top.png"); overflow: hidden; } .rock:hover { background-image: url("img/rocket_frame.png"); animation: rockMove steps(4) .4s infinite; } @keyframes rockMove { 0% { background-position-x: 0; } /* 25% { background-position-x: -150px; } 50% { background-position-x: -300px; } 75% { background-position-x: -450px; } */ 100% { background-position-x: -600px; } } </style></head><body> <div class="rock fly"> </div></body></html>带js滚动到顶部效果123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>bilibili小火箭</title> <style> * { margin: 0; padding: 0; } body,html { width: 100%; height: 1500px; } .rock { position: fixed; right: 0; bottom: 0; width: 150px; height: 174px; background-image: url("img/rocket_top.png"); overflow: hidden; display: none; } .rock:hover { background-image: url("img/rocket_frame.png"); animation: rockMove steps(4) .4s infinite; } @keyframes rockMove { 0% { background-position-x: 0; } /* 25% { background-position-x: -150px; } 50% { background-position-x: -300px; } 75% { background-position-x: -450px; } */ 100% { background-position-x: -600px; } } </style></head><body> <div class="rock fly"> </div> <script> // 获取当前视口的大小 var viewHeight = document.documentElement.clientHeight; //小火箭添加单击事件 document.querySelector(".rock").addEventListener("click", () => { //小火箭被单击,回到顶部 // document.documentElement.scrollTop = 0; //当然,也可以慢慢回到顶部 slowToTop(); }) //当然,这里使用节流会更好 window.onscroll = function () { if (document.documentElement.scrollTop >= viewHeight) { //显示小火箭元素 document.querySelector(".rock").style.display = "block"; } else { //隐藏小火箭 document.querySelector(".rock").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 -= 80; slowToTop(); } }, 1000/50); } </script></body></html>