<map> 定義客戶端圖像映射,配合 `` 在圖片上劃定可點擊熱點。本文詳細列出所有屬性、形狀座標規則、完整代碼範例與現代最佳實踐。
| 屬性 | 值類型 | 說明 |
|---|---|---|
shape | `rect` \| `circle` \| `poly` \| `default` | 熱點形狀,預設 `rect` |
coords | 字串 | 座標列表,格式見下表 |
href | URL | 連結目標,缺失則無連結(可作純標記) |
alt | 字串 | 必填,替代文字(無障礙/SEO) |
target | `_blank` \| `_self` \| `_parent` \| `_top` \| framename | 連結開啟目標 |
nohref | 布林 (HTML4) | 明確表示無連結,**HTML5 廢棄**,直接省略 `href` 即可 |
tabindex | 整數 | Tab 順序 |
accesskey | 字符 | 快捷鍵 |
rel | 字串 | 連結關係(如 `noopener`, `nofollow`) |
download | 字串/布林 | HTML5:提示下載而非導航 |
ping | URL 列表 | 點擊時發送 POST 到指定 URL(追蹤用) |
| shape | coords 格式 | 座標含義 | 範例 |
|---|---|---|---|
rect | `x1,y1,x2,y2` | 左上 (x1,y1)、右下 (x2,y2) | `10,20,110,80` |
circle | `x,y,r` | 圓心 (x,y)、半徑 r | `200,150,30` |
poly | `x1,y1,x2,y2,...,xn,yn` | 頂點序列(至少 3 對),自動閉合 | `50,0 100,50 50,100 0,50` (菱形) |
default | (無) | 整張圖片其餘區域 | — |
座標基於**原始圖片像素尺寸**,左上角為 (0,0)。
<img src="dashboard.png" usemap="#dashMap" alt="儀表板" width="800" height="600">
<map name="dashMap">
<!-- 矩形:總覽按鈕 -->
<area shape="rect" coords="20,20,180,80" href="/overview" alt="總覽" target="_blank">
<!-- 圓形:通知鈴鐺 -->
<area shape="circle" coords="750,50,25" href="/notifications" alt="通知">
<!-- 多邊形:不規則側邊欄觸發區 -->
<area shape="poly" coords="0,150, 50,150, 50,450, 0,450" href="/sidebar" alt="展開側邊欄">
<!-- 兜底:其他區域點擊回首頁 -->
<area shape="default" href="/" alt="返回首頁">
</map>
<area shape="rect" coords="10,10,100,50" data-action="openModal" data-id="123" alt="編輯">
<script>
document.querySelector('map').addEventListener('click', e => {
const area = e.target.closest('area');
if (!area) return;
e.preventDefault(); // 阻止導航
const action = area.dataset.action;
if (action === 'openModal') openModal(area.dataset.id);
});
</script>
function scaleMapAreas(mapName, displayedWidth, displayedHeight, naturalWidth, naturalHeight) {
const scaleX = displayedWidth / naturalWidth;
const scaleY = displayedHeight / naturalHeight;
document.querySelectorAll(`map[name="${mapName}"] area[coords]`).forEach(area => {
const coords = area.coords.split(',').map(Number);
const scaled = coords.map((v, i) => Math.round(v * (i % 2 === 0 ? scaleX : scaleY)));
area.coords = scaled.join(',');
});
}
// 圖片載入後調用
img.onload = () => scaleMapAreas('dashMap', img.clientWidth, img.clientHeight, img.naturalWidth, img.naturalHeight);
window.addEventListener('resize', () => scaleMapAreas(...));
如前文所述,SVG 原生支援向量縮放、CSS 樣式、動畫、語義結構,**強烈建議新專案直接用 SVG `` + 幾何圖形** 替代 `
掌握 `