<a>:Web 互聯的核心,掌握連結的所有能力與安全細節
<a> (Anchor) 定義超連結,href 指定目標 URL。現代開發需精通 target/rel 安全組合、無障礙語意、SEO 屬性、下載行為、JS 協議風險。
href 值類型完整對照
| 類型 | 範例 | 說明 |
| 絕對 URL | https://example.com/path?query=1#hash | 完整地址,跨域導航 |
| 相對 URL | /path, ../sibling, ./file.html | 相對當前頁面/目錄/根目錄 |
| 錨點連結 | #section-id, /page#section | 頁內跳轉,id="section-id" 目標元素 |
| 郵件 | mailto:user@example.com?subject=Hello&body=Content | 開啟預設郵件客戶端 |
| 電話 | tel:+886-2-12345678 | 行動裝置撥號 |
| 簡訊 | sms:+886912345678?body=Hello | 開啟簡訊應用 |
| JavaScript | javascript:doSomething() | 強烈不建議:CSP 違規、無語意、無法無障礙、SEO 無效 |
| 資料 URI | data:text/html,<h1>Hi</h1> | 小型內嵌資源,受大小限制 |
| Blob/Filesystem | blob:https://example.com/uuid | 客戶端生成的臨時資源 |
target 與 rel:安全組合拳
| target | rel (必要搭配) | 用途 | 風險 |
_blank | noopener noreferrer | 新分頁開啟 | 新頁面可透過 window.opener 竄改原頁面 (釣魚、重導向) |
_self | (預設) 無需 rel | 同分頁開啟 | 無 |
_parent | 視情境 | 父框架開啟 | 框架巢狀環境 |
_top | 視情境 | 最頂層框架開啟 | 跳出所有框架 |
framename | 視情境 | 指定 iframe name | 需同源或 COOP/COEP |
<a href="https://external.com" target="_blank" rel="noopener noreferrer">外部連結</a>
<a href="/internal" rel="nofollow">不傳遞權重 (付費/用戶生成內容)</a>
<a href="https://partner.com" rel="sponsored">贊助連結</a>
<a href="https://ugc.com" rel="ugc">用戶生成內容連結</a>
download 屬性:強制下載而非導航
<a href="report.pdf" download="2024-Q1-Report.pdf">下載報表</a>
<a href="data:text/csv;charset=utf-8,..." download="export.csv">匯出 CSV</a>
- 同源策略限制:跨域資源需配合
Content-Disposition: attachment 標頭
- 檔名建議:僅 ASCII,避免編碼問題
無障礙最佳實踐
- 連結文字需具描述性:
<a>查看 2024 年財報</a> 而非 <a>點這裡</a>
- 圖片連結:
<a><img alt="公司 Logo"></a> (alt 描述連結目的)
- 鍵盤可聚焦:預設即可,勿用
tabindex="-1" 移除
- 焦點樣式:
:focus-visible { outline: 2px solid #0066cc; outline-offset: 2px; }
aria-label / aria-labelledby:當連結無可見文字時 (純圖示)
SEO 關鍵屬性
rel="canonical":<link> 中指定規範 URL,非 <a>
hreflang:多語言版本連結 <a hreflang="en" href="/en/">English</a>
rel="nofollow/sponsored/ugc":控制權重傳遞
平滑滾動錨點導航
<a href="#section2" class="smooth-scroll">跳轉至第二節</a>
<style>
html { scroll-behavior: smooth; }
@media (prefers-reduced-motion: reduce) {
html { scroll-behavior: auto; } /* 尊重使用者偏好 */
}
</style>