<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>active 樣式 &#8211; 小豬日常</title>
	<atom:link href="https://piglife.tw/tag/active/feed/" rel="self" type="application/rss+xml" />
	<link>https://piglife.tw</link>
	<description>Hello World，一個紀錄生活與學習的地方</description>
	<lastBuildDate>Wed, 10 Dec 2025 10:22:58 +0000</lastBuildDate>
	<language>zh-TW</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://piglife.tw/wp-content/uploads/2017/10/cropped-logo-1-32x32.png</url>
	<title>active 樣式 &#8211; 小豬日常</title>
	<link>https://piglife.tw</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>利用 JavaScript 自動為當前頁面側邊欄連結加上 active 樣式</title>
		<link>https://piglife.tw/technical-notes/js-active-link-current-path/</link>
					<comments>https://piglife.tw/technical-notes/js-active-link-current-path/#respond</comments>
		
		<dc:creator><![CDATA[小豬]]></dc:creator>
		<pubDate>Wed, 10 Dec 2025 10:22:58 +0000</pubDate>
				<category><![CDATA[技術筆記]]></category>
		<category><![CDATA[active 樣式]]></category>
		<category><![CDATA[JavaScript]]></category>
		<guid isPermaLink="false">https://piglife.tw/technical-notes/js-active-link-current-path/</guid>

					<description><![CDATA[介紹如何用 JavaScript 取得當前頁面路徑並與側邊欄連結比對，動態為正確連結加上 activ...]]></description>
										<content:encoded><![CDATA[<h2 class="wp-block-heading">前言</h2>
<p>在多頁面網站中，常見需求是讓側邊欄或導覽列中的連結能自動標示當前所在頁面，提升使用者導覽體驗。這段程式碼示範如何透過 JavaScript 取得當前網頁路徑，並比對側邊欄所有連結的 href，對應到正確連結時自動加上「active」CSS 類別。適合需要動態控制導覽狀態的前端工程師或自學者。</p>
<h2 class="wp-block-heading">取得並標準化當前頁面路徑</h2>
<p>首先，我們透過 <code>window.location.pathname</code> 取得目前頁面的路徑，並轉成小寫以避免大小寫不一致問題。接著使用正則表達式移除路徑尾端多餘的斜線，確保 <code>/a/b/</code> 與 <code>/a/b</code> 被視為相同路徑。若路徑為空字串，則設定為根目錄 <code>/</code>。</p>
<pre><code class="lang-javascript language-javascript javascript">let currentPath = window.location.pathname.toLowerCase();
currentPath = currentPath.replace(/\/+$|\/$/, &quot;&quot;);
if (currentPath === &quot;&quot;) currentPath = &quot;/&quot;;</code></pre>
<h2 class="wp-block-heading">選取側邊欄連結並逐一比對</h2>
<p>使用 <code>document.querySelectorAll</code> 選取所有帶有 <code>.anchor-links .link</code> 的連結元素。對每個連結，我們先取得 <code>href</code> 屬性，並使用 <code>URL</code> 物件將相對路徑轉成絕對路徑，確保比對時不會因為相對路徑造成錯誤。</p>
<pre><code class="lang-javascript language-javascript javascript">const links = document.querySelectorAll(&quot;.anchor-links .link&quot;);
links.forEach(link =&gt; {
  const href = link.getAttribute(&quot;href&quot;);
  if (!href) return;
  const url = new URL(href, window.location.origin);
  let hrefPath = url.pathname.toLowerCase();
  hrefPath = hrefPath.replace(/\/+$/, &quot;&quot;);
  if (hrefPath === &quot;&quot;) hrefPath = &quot;/&quot;;

  if (hrefPath === currentPath) {
    link.classList.add(&quot;active&quot;);
  }
});</code></pre>
<h2 class="wp-block-heading">為何要使用 URL 物件？</h2>
<p>使用 <code>new URL(href, window.location.origin)</code> 可以將相對路徑（例如 <code>../page</code>）轉換成完整的絕對路徑，避免直接比對相對路徑時因基底路徑不同而失準。這是實務中常見的路徑比對技巧。</p>
<h2 class="wp-block-heading">實際應用場景</h2>
<ul>
<li>多層次導覽列或側邊欄，需自動標示當前頁面。</li>
<li>靜態網站或沒有後端模板渲染的情況下，前端動態控制導覽狀態。</li>
</ul>
<h2 class="wp-block-heading">延伸優化方向</h2>
<ul>
<li>可加入支援查詢字串（query string）或 hash 的比對。</li>
<li>支援部分路徑匹配，例如 <code>/blog</code> 下所有頁面都標示為 active。</li>
<li>將功能封裝成函式，方便重複使用。</li>
</ul>
<h2 class="wp-block-heading">常見問題與注意事項</h2>
<ul>
<li>確保側邊欄連結的 href 屬性正確，避免空值或錯誤路徑。</li>
<li>不同瀏覽器對 URL 物件支援度良好，但在非常舊版本可能需 polyfill。</li>
<li>若網站有使用前端路由（如 SPA），此方法需配合路由狀態更新。</li>
</ul>
<h2 class="wp-block-heading">完整程式碼</h2>
<pre><code class="lang-javascript language-javascript javascript">document.addEventListener(&quot;DOMContentLoaded&quot;, function () {
    // 目前頁面的 path，例如 /investor-relations/corporate-governance/
    let currentPath = window.location.pathname.toLowerCase();
    // 移除結尾多餘的斜線（/a/b/ -&gt; /a/b）
    currentPath = currentPath.replace(/\/+$/, &quot;&quot;);
    if (currentPath === &quot;&quot;) currentPath = &quot;/&quot;;

    const links = document.querySelectorAll(&quot;.anchor-links .link&quot;);

    links.forEach(link =&gt; {
        const href = link.getAttribute(&quot;href&quot;);
        if (!href) return;

        // 轉成絕對網址再拿 pathname，避免相對路徑問題
        const url = new URL(href, window.location.origin);
        let hrefPath = url.pathname.toLowerCase();
        hrefPath = hrefPath.replace(/\/+$/, &quot;&quot;);
        if (hrefPath === &quot;&quot;) hrefPath = &quot;/&quot;;

        // ✅ 完整匹配才加 active
        if (hrefPath === currentPath) {
            link.classList.add(&quot;active&quot;);
        }
    });
});</code></pre>]]></content:encoded>
					
					<wfw:commentRss>https://piglife.tw/technical-notes/js-active-link-current-path/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
