萬盛學電腦網

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

HTML href 標籤屬性詳解:從基本語法到圖像映射與資源預載

href 核心定義

href (Hypertext Reference) 指定連結資源的位置(URL),是超文本系統的核心屬性。

適用標籤與用途對照

標籤用途範例
<a>超連結,用戶點擊導航<a href="/about">關於我們</a>
<area>圖像映射熱區連結<area shape="circle" coords="50,50,20" href="detail.html">
<link>外部資源關聯(CSS、icon、preload、prefetch、canonical)<link rel="stylesheet" href="main.css">
<base>文檔基準 URL,影響所有相對連結<base href="https://example.com/">

URL 值類型詳解

絕對 URL
https://example.com/path?query=1#hash — 完整路徑,跨域安全。
相對 URL
./page.html、../parent/、/root/path — 相對於當前頁面或 <base> 解析。
片段識別符(錨點)
#section-id — 頁內跳轉,目標元素需有對應 id。
伪協議
mailto:email@example.com?subject=Hello、tel:+886-2-1234567、sms:、javascript:...(不推薦)。
Data URI
data:image/png;base64,iVBORw0K... — 內嵌小型資源,減少請求。

圖像映射實戰範例

<img src="map.png" usemap="#officemap" alt="辦公室平面圖">
<map name="officemap">
  <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(圓心 x,y,半徑 r)、poly(多邊形 x1,y1,x2,y2...)、default(剩餘區域)。

資源提示

<link rel="preload" href="critical.css" as="style">
<link rel="prefetch" href="next-page.html">
<link rel="preconnect" href="https://cdn.example.com">
<link rel="dns-prefetch" href="//api.example.com">

提升頁面載入性能的關鍵手段,需謹慎使用避免頻寬浪費。

安全與最佳實踐

  1. 外部連結加 rel="noopener noreferrer" 防止 window.opener 洩漏。
  2. 用戶生成內容的連結必須過濾 javascript:、data: 等危險協議。
  3. 所有 URL 經過百分號編碼,避免 XSS 與解析錯誤。
  4. 內部連結優先使用相對路徑,利於環境遷移與測試。
  5. <a> 無 href 時非真連結,無法鍵盤聚焦,請改用 <button>。
copyright © 萬盛學電腦網 all rights reserved