點擊按鈕返回頂部

一、html部分css

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

二、css部分html

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

三、js部分瀏覽器

    當頁面滾動到超過瀏覽器的大小時候,會自動出現一個div返回頂部的按鈕,當點擊以後會自動返回頂部,而後自動隱藏。spa

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);
  };
};
相關文章
相關標籤/搜索