萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML5 教學

HTML <a> 錨點連結完整指南:href 屬性、target/rel 安全屬性、無障礙、SEO、下載、JavaScript 協議、錨點導航

<a>:Web 互聯的核心,掌握連結的所有能力與安全細節

<a> (Anchor) 定義超連結,href 指定目標 URL。現代開發需精通 target/rel 安全組合、無障礙語意、SEO 屬性、下載行為、JS 協議風險。

href 值類型完整對照

類型範例說明
絕對 URLhttps://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開啟簡訊應用
JavaScriptjavascript:doSomething()強烈不建議:CSP 違規、無語意、無法無障礙、SEO 無效
資料 URIdata:text/html,<h1>Hi</h1>小型內嵌資源,受大小限制
Blob/Filesystemblob:https://example.com/uuid客戶端生成的臨時資源

target 與 rel:安全組合拳

targetrel (必要搭配)用途風險
_blanknoopener 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>
copyright © 萬盛學電腦網 all rights reserved