萬盛學電腦網

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

jQuery 實現頁面內平滑滾動錨點導航完整教學

前言

長頁面錨點跳轉預設為瞬間跳轉,用戶易迷失方向。本文示範使用 jQuery 實現「平滑滾動」錨點導航,支援垂直/水平滾動、自訂動畫時間、動態綁定,提升用戶體驗。

核心插件代碼

$.fn.anchorGoWhere = function(options) {
  const $elements = this;
  const opts = $.extend({
    target: 1,      // 1=垂直滾動, 2=水平滾動
    timer: 500      // 動畫毫秒數
  }, options);

  $elements.each(function() {
    const $el = $(this);
    $el.on('click', function(e) {
      e.preventDefault();
      const href = $(this).attr('href');
      if (!href || href === '#') return;
      const targetId = href.startsWith('#') ? href.substring(1) : href;
      const $target = $('#' + targetId);
      if (!$target.length) return;

      let scrollProp, targetPos;
      if (opts.target === 1) { // 垂直
        scrollProp = 'scrollTop';
        targetPos = $target.offset().top;
      } else { // 水平
        scrollProp = 'scrollLeft';
        targetPos = $target.offset().left;
      }

      $('html, body').animate({ [scrollProp]: targetPos }, opts.timer);
    });
  });
  return this; // 支援鏈式調用
};

使用範例

HTML 結構

<nav>
  <a href="#section1" id="btn1">去 Section 1</a>
  <a href="#section2" id="btn2">去 Section 2</a>
  <a href="#section3" id="btn3">去 Section 3</a>
</nav>

<section id="section1" style="height:800px;">內容 1</section>
<section id="section2" style="height:800px;">內容 2</section>
<section id="section3" style="height:800px;">內容 3</section>

JS 初始化

$(function() {
  // 綁定多個按鈕,統一配置
  $('#btn1, #btn2, #btn3').anchorGoWhere({ target: 1, timer: 800 });

  // 或單獨綁定不同配置
  // $('#btnHorizontal').anchorGoWhere({ target: 2, timer: 1000 });
});

進階增強

1. URL Hash 同步 (支援瀏覽器前進後退)

$elements.on('click', function(e) {
  // ... 動畫邏輯 ...
  // 動畫完成後更新 hash (不觸發跳轉)
  $('html, body').animate({ [scrollProp]: targetPos }, opts.timer, function() {
    history.pushState(null, null, '#' + targetId);
  });
});

2. 固定導航列高度補償

const headerHeight = $('#header').outerHeight();
targetPos = $target.offset().top - headerHeight;

3. 滾動監聽高亮當前區塊 (ScrollSpy)

$(window).on('scroll', function() {
  const scrollPos = $(window).scrollTop() + headerHeight + 50; // 偏移量
  $('section').each(function() {
    const $sec = $(this);
    if ($sec.offset().top <= scrollPos && $sec.offset().top + $sec.outerHeight() > scrollPos) {
      $('.nav a').removeClass('active');
      $('.nav a[href="#' + $sec.attr('id') + '"]').addClass('active');
    }
  });
});

4. 原生 JS 替代方案 (無 jQuery 依賴)

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function(e) {
    e.preventDefault();
    const targetId = this.getAttribute('href').substring(1);
    const target = document.getElementById(targetId);
    if (target) {
      target.scrollIntoView({ behavior: 'smooth', block: 'start' });
      history.pushState(null, null, '#' + targetId);
    }
  });
});

常見問題

問題原因解決
滾動後立即跳回未 e.preventDefault() 取消預設錨點跳轉事件處理開頭加上
動畫卡頓同時綁定多個 animate 於 html, body用 $('html, body').stop().animate(...) 清除佇列
目標元素找不到ID 重複、大小寫不符、元素未渲染確保 ID 唯一、DOM 就緒後綁定

總結

平滑滾動錨點導航是提升長頁面體驗的低成本高回報優化。本文提供的 anchorGoWhere 插件封裝了核心邏輯,支援垂直/水平、自訂時長、鏈式調用。現代專案可考慮原生 scrollIntoView({behavior:'smooth'}) 移除 jQuery 依賴,但需注意 Safari 舊版本相容性。

copyright © 萬盛學電腦網 all rights reserved