href (Hypertext REFerence) 指定超連結目標,用於 <a>, <link>, <area>, <base> 標籤。
| 類型 | 格式 | 範例 | 說明 |
|---|---|---|---|
| 絕對 URL | scheme://host/path | https://example.com/path/page.html | 完整路徑,跨域可用 |
| 相對 URL | path/to/resource | ./about.html, ../assets/style.css | 相對當前頁面或 <base> |
| 根相對 URL | /path | /images/logo.png | 相對網域根目錄 |
| 片段識別符 | #id | #section1, #top | 頁面內錨點,配合 id 屬性 |
| 資料協定 | data:[<mediatype>][;base64],<data> | data:image/png;base64,iVBORw0K... | 內嵌小型資源,減少請求 |
| JavaScript 協定 | javascript:code | javascript:alert('hi') | 極度不推薦,XSS 風險、CSP 違規 |
| 郵件/電話 | mailto:, tel: | mailto:user@example.com, tel:+886-2-1234567 | 啟動預設郵件/撥號App |
<base href="https://example.com/dir1/dir2/">
<a href="page.html"> <!-- https://example.com/dir1/dir2/page.html -->
<a href="./page.html"> <-- 同上 -->
<a href="../page.html"> <-- https://example.com/dir1/page.html -->
<a href="/page.html"> <-- https://example.com/page.html -->
最佳實務:避免使用 <base>,改用根相對路徑 /path 或建置工具自動處理資產路徑。
<a href="#section2">跳到第二節</a>
...
<section id="section2">...</section>
現代瀏覽器支援平滑滾動:
html { scroll-behavior: smooth; }
/* 或 JS: element.scrollIntoView({behavior: 'smooth'}) */
rel="noopener noreferrer" 防止 window.opener 洩漏、效能問題。target="_blank" 必配 rel="noopener"。javascript: 協定,改用事件監聽器 addEventListener('click', ...)。<a href="/file.pdf" download="報表.pdf"> 強制下載並重命名。alt 描述連結目的。Enter 跳轉)。