原生js實現平滑滾動


在以前的項目中有用到,在此整理一下:

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);


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM