js實現簡單的勻速回到頁面頂部。

來源:互聯網
上載者:User

標籤:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>回到頂部</title>
<style>
body{
  height:1600px;
}
.top{
  width:100%;
  height: 30px;
  background:red;
}
#box{
  width:100px;
  height:30px;
  background: pink;
  line-height: 30px;
  position: fixed;                  -->這裡注意使用固定定位。
  top:90%;
  right:40px;
  display: none;                  -->開始時將回到頂部的按鈕設定為隱藏屬性,當可視地區高度距離頁面頂部(scrolltop)的距離達到一定值時,通過改變dispaly                  使其顯示。
  cursor: pointer;
}
</style>
<script>
window.onload = function(){
  var box = document.getElementById("box");
  var top = 0;
  var timer;
  window.onscroll = function(){
    top = document.documentElement.scrollTop || document.body.scrollTop;
      if(top > 600){
        box.style.display = "block";
      }else{
        box.style.display = "none";
      }
   }
  box.onclick = function(){
    clearInterval(timer);
    var sudu = 10;
    timer = setInterval(function(){
    //console.log(top);  ----->注意測試top值,以免發生計時器未清除的情況。
    if(top <= 0){
      clearInterval(timer);  
    }else{
      document.documentElement.scrollTop = document.body.scrollTop = top - sudu;
    }
  },10);
}
}
</script>
</head>
<body>
<div class="top"></div>
<div id="box">
  點我回到頂部
</div>
</body>
</html>

js實現簡單的勻速回到頁面頂部。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.