原生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