萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery animate() 與 scrollTop 實現平滑捲動錨點導航

animate() 基礎語法

$(selector).animate({css屬性}, 速度, 緩動函數, 回呼函數);
  • 僅支援**數值型** CSS 屬性 (width, height, margin, scrollTop, opacity 等)。
  • 顏色、背景圖等非數值屬性需外掛 (如 jQuery UI / jQuery Color)。

平滑捲動到頂部/指定位置/底部

<script src="jquery.min.js"></script>
<script>
$(document).ready(function($) {
  // 回到頂部
  $('#shang').click(function() {
    $('html, body').animate({ scrollTop: '0px' }, 800);
  });

  // 捲動到指定元素 (#comments)
  $('#comt').click(function() {
    $('html, body').animate({ 
      scrollTop: $('#comments').offset().top 
    }, 800);
  });

  // 捲動到底部 (#footer)
  $('#xia').click(function() {
    $('html, body').animate({ 
      scrollTop: $('#footer').offset().top 
    }, 800);
  });
});
</script>

<!-- 導航按鈕 -->
<button id="shang">⬆ 回頂部</button>
<button id="comt">💬 看評論</button>
<button id="xia">⬇ 到底部</button>

<div id="comments" style="margin-top:2000px;">評論區</div>
<div id="footer" style="margin-top:1000px;">頁腳</div>

關鍵點解析

  1. $('html, body') 雙選擇器:跨瀏覽器相容。Chrome/FF 捲動 body,IE/Edge 捲動 html,雙選確保生效。
  2. .offset().top:取得元素相對文件的絕對座標,作為捲動目標。
  3. 速度 800ms:體感平滑,可依設計調整 (300-1000ms 常見)。
  4. 緩動函數:預設 swing,可改 linear 或引入 jQuery UI 使用 easeInOutCubic 等進階緩動。

進階:動態偏移量 (固定導覽列高度補償)

var navHeight = $('#fixedNav').outerHeight(); // 固定導覽列高度

$('#comt').click(function() {
  var targetTop = $('#comments').offset().top - navHeight;
  $('html, body').animate({ scrollTop: targetTop }, 800);
});

進階:捲動完成後更新 URL Hash (不跳動)

$('#comt').click(function(e) {
  e.preventDefault(); // 阻止預設錨點跳轉
  var target = $('#comments');
  var targetTop = target.offset().top - navHeight;
  
  $('html, body').animate({ scrollTop: targetTop }, 800, function() {
    // 動畫完成後更新 hash (不觸發捲動)
    history.pushState(null, null, '#comments');
    // 或:window.location.hash = 'comments'; (會微微跳動)
  });
});

現代原生替代:scrollTo + behavior: 'smooth'

無需 jQuery,現代瀏覽器原生支援:

document.getElementById('shang').addEventListener('click', function() {
  window.scrollTo({ top: 0, behavior: 'smooth' });
});

document.getElementById('comt').addEventListener('click', function() {
  var target = document.getElementById('comments');
  var navHeight = document.getElementById('fixedNav').offsetHeight;
  window.scrollTo({ top: target.offsetTop - navHeight, behavior: 'smooth' });
});

支援:Chrome 61+、Firefox 36+、Safari 14+、Edge 79+。IE 不支援,需 Polyfill (smoothscroll)。

無障礙建議

  • 按鈕加 aria-label 說明用途。
  • 鍵盤可聚焦 (tabindex="0" 或原生 <button>)。
  • 提供「跳過到主要內容」連結 (<a href="#main">跳過導航</a>)。
copyright © 萬盛學電腦網 all rights reserved