萬盛學電腦網

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

HTML <a> 標籤 href 屬性進階應用:超連結、圖像映射、資源預載與安全屬性

<a> href 核心屬性

<a href="URL" target="_blank" rel="noopener noreferrer" hreflang="zh-Hant" download="filename.pdf">連結文字</a>
屬性說明常用值
href目標 URL (必填)絕對/相對/錨點/mailto/tel/javascript/data URI
target開啟位置_blank(新分頁)、_self(預設)、_parent、_top、iframe名稱
rel關係/安全noopener(斷開 opener)、noreferrer(不送 Referer)、nofollow(SEO)、preload、prefetch
hreflang目標語言zh-Hant、en-US、ja 等 BCP 47 標籤
download強制下載並指定檔名僅同源生效
ping點擊時送 POST 到 URL 列表 (追蹤)空格分隔多 URL
referrerpolicyReferer 政策no-referrer、origin、strict-origin-when-cross-origin 等

圖像映射 <map> + <area href>

<img src="floorplan.png" usemap="#rooms" alt="樓層平面圖">
<map name="rooms">
  <area shape="rect" coords="10,10,100,80" href="/room/101" alt="會議室 101">
  <area shape="circle" coords="200,150,30" href="/room/201" alt="休息區">
  <area shape="poly" coords="300,50,350,100,250,100" href="/room/301" alt="經理室">
  <area shape="default" href="/directory" alt="其他區域">
</map>

shape:rect(x1,y1,x2,y2)、circle(cx,cy,r)、poly(x1,y1,x2,y2...)、default(剩餘區域)。

<link> href 資源提示

<link rel="stylesheet" href="main.css">
<link rel="preload" href="critical.woff2" as="font" type="font/woff2" crossorigin>
<link rel="prefetch" href="next-page.html">
<link rel="preconnect" href="https://cdn.example.com">
<link rel="dns-prefetch" href="//api.example.com">
<link rel="canonical" href="https://example.com/canonical-url">
  • preload:當前頁必須、高優先級資源 (字體、關鍵 CSS/JS)。
  • prefetch:未來頁面可能用到的資源 (低優先級)。
  • preconnect:提前建立 TCP/TLS 連線 (跨域關鍵域名)。
  • canonical:告訴搜尋引擎標準網址,避免重複內容。

<base> href 全域基準

<head>
  <base href="https://example.com/app/" target="_blank">
</head>
<body>
  <a href="page.html">實際解析為 https://example.com/app/page.html</a>
</body>

全文檔僅能出現一個,置於 <head> 內,影響所有相對連結 (含 <img src>、<script src>、<link href>)。

安全最佳實踐

  1. 外部連結 target="_blank" 必加 rel="noopener noreferrer",防止 window.opener 被惡意導向。
  2. 用戶生成連結:後端過濾 javascript:、data:、vbscript: 等危險協議;前端二次檢查。
  3. 所有 URL 經過 encodeURIComponent() 處理動態參數。
  4. CSP 政策限制 navigate-to、form-action 導向範圍。

無障礙檢查

  • 連結文字具描述性,避免「點這裡」、「更多」。
  • 同一 URL 不重複出現多個無意義連結文字。
  • aria-label / aria-labelledby 補充隱藏連結文字。
  • 鍵盤可聚焦、可操作,焦點樣式明顯 (:focus-visible)。
copyright © 萬盛學電腦網 all rights reserved