DIV CSS 佈局教程網

純文字「返回頂部」連結的 JS 實作
編輯:關於JavaScript     

在內容較長的頁面裡,「返回頂部」是一個貼心的小功能。這個範例不使用任何圖片,只用一個純文字連結搭配 JavaScript,就能實現平滑回到頁面頂端的滾動效果。

平滑滾動的原理

關鍵在於 goto_top_timer() 函數:它透過 setInterval 每 50 毫秒觸發一次,每次把捲動位置削減為目前的 moveby / 100(這裡是 15%),形成「越接近頂部移動越慢」的緩動視覺效果,直到 y 歸零時清除計時器。

<script language="javascript">
var goto_top_type = -1;
var goto_top_itv = 0;
function goto_top_timer() {
 var y = goto_top_type == 1 ? document.documentElement.scrollTop
  : document.body.scrollTop;
 var moveby = 15;
 y -= Math.ceil(y * moveby / 100);
 if (y < 0) {
  y = 0;
 }
 if (goto_top_type == 1) {
  document.documentElement.scrollTop = y;
 } else {
  document.body.scrollTop = y;
 }
 if (y == 0) {
  clearInterval(goto_top_itv);
  goto_top_itv = 0;
 }
}
function goto_top() {
 if (goto_top_itv == 0) {
  if (document.documentElement && document.documentElement.scrollTop) {
   goto_top_type = 1;
  } else if (document.body && document.body.scrollTop) {
   goto_top_type = 2;
  } else {
   goto_top_type = 0;
  }
  if (goto_top_type > 0) {
   goto_top_itv = setInterval('goto_top_timer()', 50);
  }
 }
}
</script>
<a href="javascript:void(0)" onclick="goto_top()">【返回頂部】</a>

相容性考量

程式碼透過 goto_top_type 變數判斷該操作 document.documentElement.scrollTop 還是 document.body.scrollTop,以相容不同瀏覽器的捲動屬性差異。這種百分比遞減的緩動寫法,比瞬間跳回頂部更能帶來舒適的使用感受。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved