用js實現簡單的點擊返回頂部效果

轉自http://www.cnblogs.com/jingangel/archive/2012/03/08/2385939.html

當頁面特別長的時候,用戶想回到頁面頂部,必須得滾動好幾次滾動鍵才能回到頂部,如果在頁面右下角有個“返回頂部”的按鈕,用戶點擊一下,就可以回到頂部,對于用戶來說,是一個比較好的體驗。

實現原理:當頁面加載的時候,把元素定位到頁面的右下角,當頁面滾動時,元素一直位于右下角,當用戶點擊的時候,頁面回到頂部。

要點一:document.documentElement.clientWidth || document.body.clientWidth; 獲得可視區的寬度。后面是兼容chrome,前面是兼容其它瀏覽器。

要點二:oTop.style.left = screenw - oTop.offsetWidth +"px"; 當頁面加載時,讓元素的位置位于頁面最右邊,用可視區的寬度減去元素本身的寬度。

要點三:oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px"; 當頁面滾動時,元素的Y坐標位置等于可視區的高度減去元素本身的高度,加上滾動距離。

要點四:document.documentElement.scrollTop = document.body.scrollTop =0; 當點擊元素時,讓頁面的滾動距離為0.寫兩個是為了兼容。

上代碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>無標題文檔</title>
<style>
body{margin:0; padding:0}
#to_top{width:30px; height:40px; padding:20px; font:14px/20px arial; text-align:center;  background:#06c; position:absolute; cursor:pointer; color:#fff}
</style>
<script>
window.onload = function(){
  var oTop = document.getElementById("to_top");
  var screenw = document.documentElement.clientWidth || document.body.clientWidth;
  var screenh = document.documentElement.clientHeight || document.body.clientHeight;
  oTop.style.left = screenw - oTop.offsetWidth +"px";
  oTop.style.top = screenh - oTop.offsetHeight + "px";
  window.onscroll = function(){
    var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
    oTop.style.top = screenh - oTop.offsetHeight + scrolltop +"px";
  }
  oTop.onclick = function(){
    document.documentElement.scrollTop = document.body.scrollTop =0;
  }
}  

</script>
</head>

<body style="height:1000px;">

<h1>返回頂部</h1>


<div id="to_top">返回頂部</div>
</body>
</html>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容