在之前的項目中有用到,在此整理一下:javascript
html部分html
<span id="gotop">回到頂部</span>
JS部分java
// 使用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);