DIV CSS 佈局教程網

兩行代碼搞定 jQuery 平滑跳轉到頁面頂部與底部
編輯:JavaScript綜合知識     

長頁面總需要「回到頂部」和「跳到 }底部」的入口。用 jQuery 的 animate 動畫操作 scrollTop,兩三行就能實現平滑滾動,比瞬間跳躍的體驗好得多。

完整示例

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>Untitled Page</title>
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script>
$(document).ready(function () {
  // 點擊頂部按鈕:scrollTop 為 0 即回到頁面最上方
  $('#top').click(function () {
    $('html').animate({ scrollTop: '0px' }, 1000);
  });

  // 點擊底部按鈕:offset().top 給出元素相對於文檔的偏移
  $('#foot').click(function () {
    $('html').animate({ scrollTop: $('span').offset().top }, 1000);
  });
});
</script>
</head>
<body>
<br /><br /><br /><br /><br />
<a href="#" id="foot">底部</a>
<br /><br /><br /><br /><br />
<br /><br /><br /><br /><br />

<a href="#" id="top">頂部</a>
<br /><br /><br /><br /><br />
<span></span>
</body>
</html>

原理

回頂部很直接:scrollTop 屬性代表元素被滾動的距離,把它動畫到 0,視口自然回到最上方。

跳到底部則需要知道目標位置。offset() 返回匹配元素相對於文檔的偏移量,是一個帶 top 和 left 兩個屬性的對象。示例在頁面末尾放了一個空的 <span></span> 作為「底部標記」,取它的 offset().top 就是我們要滾動到的目標值。

animate 的第二個參數控制時長,除了具體毫秒數,也可以直接寫 'slow'、'normal' 或 'fast'。

幾點實踐改進

同時兼容更多瀏覽器。只選中 $('html') 在部分 WebKit 環境下不生效,滾動容器實際上是 body。實戰中常寫成 $('html, body').animate(...) 一起動畫,覆蓋面更全。

防止動畫堆積。用戶連點幾次「回頂部」,會排隊執行多個動畫。加上 .stop(true) 可以中止隊列中的舊動畫,避免畫面反覆抖動。

平滑滾動的現代做法。如果只是要效果而不需要自定義曲線,CSS 一行就夠了:html { scroll-behavior: smooth; },配合 element.scrollIntoView({ behavior: 'smooth' }) 使用,無需引入 jQuery。

無障礙考慮。點擊 href="#" 的鏈接會讓 URL 追加井號並把焦點移到頁首,建議補上 return false 或改用 button 元素。另外,部分用戶在系統層面開啟了「減少動態效果」,可以通過 prefers-reduced-motion 媒體查詢關閉平滑滾動。

底部標記的替代方案。用一個空 span 來標記底部略顯取巧,直接計算 $(document).height() - $(window).height() 更直觀,也不需要在頁面裡塞無語義的占位元素。

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