function backToTop () { cancelAnimationFrame(timer); // 获取当前毫秒数 const startTime = Date.now(); // 获取当前页面的滚动高度 const scrollTop = document.body.scrollTop || document.documentElement.scrollTop; // 滚动周期时间 let interval = 500; timer = requestAnimationFrame(function scrollFunc(){ // 已执行时间 let executeTime = Date.now() - startTime; // 剩余滚动距离 document.documentElement.scrollTop = document.body.scrollTop = scrollTop - (executeTime / interval * scrollTop); timer = requestAnimationFrame(scrollFunc); if(executeTime >= interval){ cancelAnimationFrame(timer); } }); }