萬盛學電腦網

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

jQuery 平滑滾動到錨點:animate scrollTop 完整指南與原生 scrollIntoView 替代

jQuery 經典實現

<!-- HTML -->
<a href="#section3" class="scroll-link">跳轉到第 3 節</a>
<!-- ... 長內容 ... -->
<h2 id="section3">第 3 節</h2>

<script>
$(function () {
  $('.scroll-link').on('click', function (e) {
    e.preventDefault(); // 阻止默認跳轉(URL 不變、無歷史記錄)

    var targetId = this.hash; // '#section3'
    var $target = $(targetId);

    if ($target.length) {
      $('html, body').animate({
        scrollTop: $target.offset().top
      }, {
        duration: 500,
        easing: 'swing', // 或 'linear'
        complete: function () {
          // 可選:聚焦目標提升無障礙
          $target.attr('tabindex', '-1').focus();
          // 可選:更新 URL hash(不跳轉)
          // history.pushState(null, null, targetId);
        }
      });
    }
  });
});
</script>

關鍵參數詳解

參數說明推薦值
scrollTop目標垂直滾動位置(像素)$target.offset().top 或 $target.offset().top - fixedHeaderHeight
duration動畫時長(毫秒)300-800,視距離而定
easing緩動函數'swing'(預設) / 'linear' / jQuery UI easing
complete完成回調聚焦、更新 hash、觸發曝光統計

常見問題與修正

1. 固定導航欄遮擋目標

var headerHeight = $('#header').outerHeight(); // 含邊框/內邊距
$('html, body').animate({
  scrollTop: $target.offset().top - headerHeight - 10 // 額外 10px 留白
}, 500);

2. 動態內容導致 offset 不準

// 在圖片載入後、字體加載後重新計算
$target.imagesLoaded ? $target.imagesLoaded(doScroll) : doScroll();

function doScroll() {
  var top = $target.offset().top - headerHeight;
  $('html, body').animate({ scrollTop: top }, 500);
}

3. 移動端觸摸衝突

// 禁用頁面原生觸摸滾動(謹慎使用)
// $('html, body').on('touchmove', function(e){ e.preventDefault(); });

// 更好:使用 passive: false 僅在動畫期間禁用
var scrolling = false;
function smoothScroll(target, duration) {
  scrolling = true;
  $('html, body').animate({scrollTop: target}, {
    duration: duration,
    complete: function () { scrolling = false; }
  });
}
$(window).on('touchmove', function (e) { if (scrolling) e.preventDefault(); }, {passive: false});

現代原生替代:element.scrollIntoView()

// 最簡單
document.getElementById('section3').scrollIntoView({ behavior: 'smooth' });

// 進階選項
target.scrollIntoView({
  behavior: 'smooth',     // 'auto' | 'smooth'
  block: 'start',         // 'start' | 'center' | 'end' | 'nearest' (垂直對齊)
  inline: 'nearest'       // 水平對齊
});

支援情況

原生版完整封裝(含固定 Header 修正)

function smoothScrollTo(target, options) {
  options = Object.assign({
    behavior: 'smooth',
    block: 'start',
    headerSelector: '#header', // 固定頭部選擇器
    offset: 10                 // 額外留白
  }, options);

  var header = document.querySelector(options.headerSelector);
  var headerH = header ? header.offsetHeight : 0;

  // 暫時修正目標位置(scrollIntoView 無原生 offset 選項)
  var originalTop = target.style.scrollMarginTop;
  target.style.scrollMarginTop = (headerH + options.offset) + 'px';

  target.scrollIntoView({ behavior: options.behavior, block: options.block });

  // 動畫結束後恢復(近似,實際需監聽 scrollend 事件)
  setTimeout(function () { target.style.scrollMarginTop = originalTop; }, 1000);
}

無障礙檢查清單

  • [ ] 錨點連結有 href="#id",無 JS 也可跳轉
  • [ ] 目標元素有 id 對應
  • [ ] 動畫完成後 focus() 目標(螢幕閱讀器跟隨)
  • [ ] 提供「跳過動畫」選項(prefers-reduced-motion)
  • [ ] 更新 URL hash 可選(history.pushState),不破壞返回鍵

CSS scroll-behavior 一鍵啟用(最簡單)

<style>
  html {
    scroll-behavior: smooth; /* 全頁錨點平滑滾動,無需 JS */
  }
  @media (prefers-reduced-motion: reduce) {
    html { scroll-behavior: auto; } /* 尊重用戶偏好 */
  }
</style>

⚠️ 無法控制速度、偏移量、回調。適合簡單頁內跳轉。

結語

平滑滾動三層選擇:**CSS `scroll-behavior` 最簡**、**原生 `scrollIntoView` 標準**、**jQuery `animate` 最大控制力**。新專案優先 CSS + 原生 API 組合;舊專案維護 jQuery 代碼時,注意固定 Header 偏移、動態內容重算、移動端觸摸衝突三大坑。無障礙細節決定產品專業度。

copyright © 萬盛學電腦網 all rights reserved