萬盛學電腦網

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

jQuery 實現電商類網站浮動導航菜單:滾動定位與高亮聯動

效果拆解

浮動導航在長單頁(如電商樓層、文檔目錄)中極為常見,核心包含兩大功能:

  1. 點擊導航 → 平滑滾動到對應樓層(錨點 + animate)
  2. 頁面滾動 → 導航項自動高亮當前樓層(scroll 事件 + 位置計算)

HTML 結構規範

<!-- 浮動導航 -->
<nav id="floorNav" class="floor-nav">
  <ul>
    <li><a href="#floor1" class="current">1F 男裝</a></li>
    <li><a href="#floor2">2F 女裝</a></li>
    <li><a href="#floor3">3F 美妝</a></li>
    <li><a href="#floor4">4F 數碼</a></li>
    <li><a href="#floor5">5F 母嬰</a></li>
  </ul>
</nav>

<!-- 內容樓層 -->
<main id="content">
  <section id="floor1" class="floor"><h2>1F 男裝</h2>...</section>
  <section id="floor2" class="floor"><h2>2F 女裝</h2>...</section>
  <section id="floor3" class="floor"><h2>3F 美妝</h2>...</section>
  <section id="floor4" class="floor"><h2>4F 數碼</h2>...</section>
  <section id="floor5" class="floor"><h2>5F 母嬰</h2>...</section>
</main>

CSS 關鍵點

.floor-nav {
  position: fixed;
  left: 50%;
  margin-left: 600px; /* 相對頁面居中偏移 */
  top: 200px;
  z-index: 999;
  background: #fff;
  box-shadow: 0 2px 8px rgba(0,0,0,.15);
  border-radius: 4px;
}
.floor-nav ul { padding: 10px 0; }
.floor-nav a {
  display: block;
  width: 80px; height: 40px;
  line-height: 40px;
  text-align: center;
  color: #333;
  text-decoration: none;
  font-weight: 500;
}
.floor-nav a:hover,
.floor-nav a.current {
  color: #fff;
  background: #0088bb;
}
.floor { padding: 40px 0; min-height: 500px; }

jQuery 核心邏輯(優化版)

$(function () {
  var $nav = $('#floorNav');
  var $navLinks = $nav.find('a');
  var $floors = $('#content .floor');
  var navHeight = $nav.outerHeight();
  var throttleTimer = null;

  // 1. 點擊導航 → 平滑滾動
  $navLinks.on('click', function (e) {
    e.preventDefault();
    var targetId = $(this).attr('href');
    var $target = $(targetId);
    if ($target.length) {
      var offsetTop = $target.offset().top;
      // 若有固定頭部,需減去頭部高度
      $('html, body').stop(true).animate({ scrollTop: offsetTop }, 600, function () {
        // 動畫結束可選更新 URL hash
        // history.pushState(null, null, targetId);
      });
    }
  });

  // 2. 滾動監聽 → 高亮聯動(節流優化)
  $(window).on('scroll', function () {
    if (throttleTimer) return;
    throttleTimer = setTimeout(function () {
      throttleTimer = null;
      updateActiveNav();
    }, 30); // ~30fps 節流
  });

  function updateActiveNav() {
    var scrollTop = $(window).scrollTop();
    var winHeight = $(window).height();
    var docHeight = $(document).height();

    // 邊界處理:滾動到底部時強制高亮最後一項
    if (scrollTop + winHeight >= docHeight - 50) {
      setActive($navLinks.last());
      return;
    }

    // 正常情況:計算每個樓層的進入/離開閾值
    var currentId = '';
    $floors.each(function () {
      var $floor = $(this);
      var floorTop = $floor.offset().top;
      var floorHeight = $floor.outerHeight();
      // 閾值:樓層頂部進入視口上方 200px 時激活(可配置)
      if (scrollTop > floorTop - 200) {
        currentId = '#' + $floor.attr('id');
      }
    });

    if (currentId) {
      setActive($navLinks.filter('[href="' + currentId + '"]'));
    }
  }

  function setActive($link) {
    if (!$link.length || $link.hasClass('current')) return;
    $navLinks.removeClass('current');
    $link.addClass('current');
  }

  // 初始化執行一次
  updateActiveNav();
});

關鍵優化細節

優化點說明
節流scroll 事件高頻觸發,使用 setTimeout 或 requestAnimationFrame 節流,避免主線程阻塞
緩存選擇器$navLinks、$floors 在 ready 時緩存,避免重複查詢 DOM
止動畫隊列.stop(true) 防止連點導致動畫排隊
邊界修正頂部偏移量、底部兜底邏輯、固定頭部高度扣除
IntersectionObserver 替代現代瀏覽器可用 IO 替代 scroll 監聽,性能更優、代碼更簡潔

現代化重寫:IntersectionObserver 版

// 僅現代瀏覽器,IE 需 Polyfill
var observer = new IntersectionObserver(function (entries) {
  entries.forEach(function (entry) {
    if (entry.isIntersecting) {
      var id = entry.target.id;
      $navLinks.removeClass('current');
      $navLinks.filter('[href="#' + id + '"]').addClass('current');
    }
  });
}, {
  rootMargin: '-200px 0px -60% 0px', // 頂部提前 200px 觸發,底部保留 60%
  threshold: 0
});

$floors.each(function () {
  observer.observe(this);
});

優勢:無需 scroll 監聽、無節流邏輯、瀏覽器原生優化、自動處理邊界。
兼容:IE 需引入 官方 Polyfill。

無障礙增強

總結

浮動導航的核心是「位置計算」與「狀態同步」。傳統 scroll + offset 方案兼容性好但需手動優化性能;IntersectionObserver 方案現代、高效、聲明式。建議新項目優先用 IO + Polyfill,老項目沿用 scroll 方案但必須加節流、緩存、邊界修正。無論哪種實現,無障礙屬性與減弱動畫偏好都是專業級代碼的標配。

copyright © 萬盛學電腦網 all rights reserved