萬盛學電腦網

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

導航列點擊切換 Active 狀態:原生 JS 與 jQuery 實作對比

單頁應用 (SPA) 與傳統多頁網站都需要導航列的「當前頁面高亮」功能。本文提供原生 JavaScript 與 jQuery 兩種實作方案,涵蓋動態新增頁面、URL 同步、無障礙屬性等實務需求。

核心邏輯:互斥類別切換

本質上是「移除所有同層項目的 active 類別,再給當前項目加上 active」的互斥操作。

方案一:現代原生 JavaScript (推薦)

<nav id="mainNav" aria-label="主要導航">
  <ul class="nav-list" role="menubar">
    <li role="none"><a href="#home" role="menuitem" class="nav-link active">首頁</a></li>
    <li role="none"><a href="#products" role="menuitem" class="nav-link">產品</a></li>
    <li role="none"><a href="#about" role="menuitem" class="nav-link">關於我們</a></li>
    <li role="none"><a href="#contact" role="menuitem" class="nav-link">聯絡我們</a></li>
  </ul>
</nav>

<style>
  .nav-list { display: flex; list-style: none; padding: 0; margin: 0; gap: 4px; }
  .nav-link {
    display: block;
    padding: 12px 20px;
    color: #333;
    text-decoration: none;
    border-radius: 6px;
    transition: all 0.2s ease;
    font-weight: 500;
  }
  .nav-link:hover { background: #f0f0f0; color: #007bff; }
  .nav-link.active { 
    background: #007bff; 
    color: #fff; 
    box-shadow: 0 2px 8px rgba(0,123,255,0.3);
  }
  .nav-link:focus-visible { outline: 2px solid #007bff; outline-offset: 2px; }
</style>

<script>
(function() {
  var nav = document.getElementById('mainNav');
  var links = nav.querySelectorAll('.nav-link');
  
  // 1. 點擊切換
  nav.addEventListener('click', function(e) {
    var link = e.target.closest('.nav-link');
    if (!link) return;
    
    e.preventDefault(); // SPA 模式阻止跳轉
    
    // 互斥切換
    links.forEach(function(l) { l.classList.remove('active'); });
    link.classList.add('active');
    
    // 觸發自訂事件,供路由系統監聽
    var event = new CustomEvent('nav:change', { 
      detail: { hash: link.getAttribute('href'), element: link } 
    });
    nav.dispatchEvent(event);
  });
  
  // 2. 根據 URL Hash 自動同步 (頁面載入/前進後退)
  function syncActiveFromHash() {
    var hash = window.location.hash || '#home';
    var target = nav.querySelector('.nav-link[href="' + hash + '"]');
    if (target) {
      links.forEach(function(l) { l.classList.remove('active'); });
      target.classList.add('active');
    }
  }
  
  window.addEventListener('hashchange', syncActiveFromHash);
  window.addEventListener('load', syncActiveFromHash);
  
  // 3. 鍵盤無障礙:左右鍵切換
  nav.addEventListener('keydown', function(e) {
    var activeLink = nav.querySelector('.nav-link.active');
    var index = Array.from(links).indexOf(activeLink);
    var newIndex = index;
    
    if (e.key === 'ArrowRight') newIndex = (index + 1) % links.length;
    else if (e.key === 'ArrowLeft') newIndex = (index - 1 + links.length) % links.length;
    else return;
    
    e.preventDefault();
    links[newIndex].focus();
    links[newIndex].click(); // 觸發點擊邏輯
  });
})();
</script>

方案二:jQuery 經典寫法 (維護舊專案用)

<div id="container">
  <ul id="Menu">
    <li><a href="javascript:;" class="current">選單一</a></li>
    <li><a href="javascript:;">選單二</a></li>
    <li><a href="javascript:;">選單三</a></li>
    <li><a href="javascript:;">選單四</a></li>
    <li><a href="javascript:;">選單五</a></li>
  </ul>
</div>

<style>
  #container ul { list-style: none; padding: 0; margin: 0; display: flex; }
  #container ul li { margin-right: 8px; }
  #container ul li a { 
    display: block; padding: 10px 18px; 
    color: #333; text-decoration: none; 
    border-radius: 4px; transition: background 0.2s;
  }
  #container ul li a:hover { background: #eee; }
  .current { background: #dc3545 !important; color: #fff !important; }
</style>

<script>
$(function() {
  var $menu = $('#Menu');
  
  $menu.on('click', 'a', function(e) {
    e.preventDefault();
    $menu.find('a').removeClass('current');
    $(this).addClass('current');
    
    // 觸發自訂事件
    $menu.trigger('nav:change', [this.hash, this]);
  });
  
  // Hash 同步
  $(window).on('hashchange load', function() {
    var hash = window.location.hash || '#home';
    var $target = $menu.find('a[href="' + hash + '"]');
    if ($target.length) {
      $menu.find('a').removeClass('current');
      $target.addClass('current');
    }
  });
});

進階功能擴充

1. 動態新增/移除導航項目

// 原生 JS 版
function addNavItem(href, text, index) {
  var nav = document.getElementById('mainNav');
  var list = nav.querySelector('.nav-list');
  var li = document.createElement('li');
  li.role = 'none';
  li.innerHTML = '<a href="' + href + '" role="menuitem" class="nav-link">' + text + '</a>';
  
  if (typeof index === 'number' && index < list.children.length) {
    list.insertBefore(li, list.children[index]);
  } else {
    list.appendChild(li);
  }
  // 重新獲取 links (或使用事件委派已自動生效)
}

function removeNavItem(href) {
  var link = document.querySelector('.nav-link[href="' + href + '"]');
  if (link) link.parentElement.remove();
}

2. 巢狀下拉選單支援

<ul class="nav-list">
  <li class="has-dropdown">
    <a href="#products" class="nav-link">產品 <span class="arrow">▼</span></a>
    <ul class="submenu">
      <li><a href="#laptops" class="nav-link">筆電</a></li>
      <li><a href="#phones" class="nav-link">手機</a></li>
    </ul>
  </li>
</ul>

<style>
  .has-dropdown { position: relative; }
  .submenu { 
    position: absolute; top: 100%; left: 0; 
    display: none; min-width: 180px; background: #fff; 
    box-shadow: 0 4px 12px rgba(0,0,0,.15); border-radius: 0 0 6px 6px;
  }
  .has-dropdown:hover .submenu, .has-dropdown:focus-within .submenu { display: block; }
  .submenu .nav-link { padding: 10px 16px; white-space: nowrap; }
</style>

3. 響應式漢堡選單整合

<button class="hamburger" aria-expanded="false" aria-controls="mainNav" aria-label="切換選單">
  <span class="bar"></span><span class="bar"></span><span class="bar"></span>
</button>

<style>
  .hamburger { display: none; flex-direction: column; gap: 5px; background: none; border: none; cursor: pointer; padding: 8px; }
  .hamburger .bar { width: 24px; height: 2px; background: #333; transition: transform 0.3s; }
  @media (max-width: 768px) {
    .hamburger { display: flex; }
    .nav-list { position: absolute; top: 100%; left: 0; right: 0; flex-direction: column; background: #fff; display: none; box-shadow: 0 4px 12px rgba(0,0,0,.1); }
    .nav-list.open { display: flex; }
    .hamburger.open .bar:nth-child(1) { transform: rotate(45deg) translate(5px, 5px); }
    .hamburger.open .bar:nth-child(2) { opacity: 0; }
    .hamburger.open .bar:nth-child(3) { transform: rotate(-45deg) translate(5px, -5px); }
  }
</style>

<script>
document.querySelector('.hamburger').addEventListener('click', function() {
  this.classList.toggle('open');
  document.querySelector('.nav-list').classList.toggle('open');
  this.setAttribute('aria-expanded', this.classList.contains('open'));
});

SPA 路由整合範例

// 監聽導航變更,交給路由器處理
document.getElementById('mainNav').addEventListener('nav:change', function(e) {
  var hash = e.detail.hash; // 如 #products
  router.navigate(hash); // 你的路由器實作
});

// 路由器切換視圖後,回呼同步導航
router.on('routeChanged', function(route) {
  syncActiveFromHash(); // 復用前面的同步函式
});

導航列是網站的「目錄與指南針」,良好的 Active 狀態管理不僅提升使用者導向感,更是無障礙與 SEO 的基礎建設。

copyright © 萬盛學電腦網 all rights reserved