在以前的项目中有用到,在此整理一下:
html部分
<span id="gotop">回到顶部</span>
JS部分
// 使用requestAnimationFrame代替setTimeout
// requestAnimationFrame随显示器刷新一帧而执行一次函数,更精确
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (fn) {
return setTimeout(fn, 17);
};
} let target = document.querySelector("#gotop"); target.onclick = function(){
timer = requestAnimationFrame(function(){
// 页面滚动的距离
let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
// 控制滚动速率
let speed = Math.floor(-scrollTop / 6);
if(scrollTop < 1){
if (window.cancelAnimationFrame) {
window.cancelAnimationFrame(timer)
} else {
clearInterval(timer);
}
document.documentElement.scrollTop = document.body.scrollTop = scrollTop + speed;
})
}
window.cancelAnimationFrame(aid);