zoukankan      html  css  js  c++  java
  • 原生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);
  • 相关阅读:
    checkbox radio select 选中总结
    vue-cli3总结
    数组总结
    Object 总结
    ajax总结
    canvas
    移动端事件
    微服务架构 SpringBoot(一)
    spring+activemq实战之配置监听多队列实现不同队列消息消费
    Integer 数值比较
  • 原文地址:https://www.cnblogs.com/dll-ft/p/10752474.html
Copyright © 2011-2022 走看看