点击按钮返回顶部

1、html部分

<div class='a'>
    <div class='b'></div>
</div>
<div id="btn">返回顶部</div>

2、css部分

    div.a{

        width:300px;
        height:10000px;
    }
    div.b{
        width:100%;    
        height:950px;
        position:relative;
        background:yellow;
    }
    #btn{
        position: fixed;
        bottom:20px;
        right:20px;
        width:100px;
        height:100px;
        border:1px solid red;
        display: none;
    }

3、js部分

    当页面滚动到超过浏览器的大小时候,会自动出现一个div返回顶部的按钮,当点击之后会自动返回顶部,然后自动隐藏。

window.onload = function(){
  var btn = document.getElementById('btn');
  var timer = null;
  var isTop = true;
  //获取页面可视区高度
  var clientHeight = document.documentElement.clientHeight;
 console.log(clientHeight)
   
  //滚动条滚动时触发
  window.onscroll = function() {
  //显示回到顶部按钮
    var osTop = document.documentElement.scrollTop || document.body.scrollTop;
    if (osTop >= clientHeight) {
      btn.style.display = "block";
    } else {
      btn.style.display = "none";
    };
  //回到顶部过程中用户滚动滚动条,停止定时器
    if (!isTop) {
      clearInterval(timer);
    };
    isTop = false;
 
  };
 
  btn.onclick = function() {
    //设置定时器
    timer = setInterval(function(){
      //获取滚动条距离顶部高度
      var osTop = document.documentElement.scrollTop || document.body.scrollTop;
      console.log('osTop '+osTop);
      var ispeed = Math.floor(-osTop / 7);
       console.log('ispeed '+ispeed);
      document.documentElement.scrollTop = document.body.scrollTop = osTop+ispeed;
      //到达顶部,清除定时器
      if (osTop == 0) {
        clearInterval(timer);
      };
      isTop = true;
       
    },30);
  };
};
原文地址:https://www.cnblogs.com/weiyf/p/6872504.html