rect形状的coords必须是四个整数,顺序为"x1,y1,x2,y2",代表左上角和右下角绝对像素坐标,须基于图片原始尺寸,缩放后需js动态换算,且usemap与map的name必须严格配对。

rect形状的coords必须是四个整数,顺序不能错
写 area 标签时,shape="rect" 对应的 coords 只能且必须是四个整数,格式为 "x1,y1,x2,y2",中间用英文逗号分隔、**不能有空格**。它代表矩形左上角 (x1, y1) 和右下角 (x2, y2) 的绝对像素位置——不是宽高,不是中心点,也不是百分比。
常见错误包括:
-
coords="100,50,100,100":右下 x 等于左上 x,区域退化成一条线,热区失效 -
coords="20,30,120,80":误把“距左 20px、宽 120px”直接当坐标填,实际应填"20,30,140,110"(x2 = x1 + width,y2 = y1 + height) - 用 Figma 或 PS 量坐标时,以图层画布原点为基准,而非图片自身左上角
(0,0)
坐标必须基于图片原始尺寸,缩放后会失效
浏览器只认 img.naturalWidth 和 img.naturalHeight 下的像素值。哪怕你加了 style="width: 50%" 或 max-width: 100%,coords 也得按原始图尺寸填写——它不会自动缩放,也不会报错,只是点不中。
如果图片显示尺寸经常变,建议用 JS 动态换算:
const img = document.querySelector('img');
const scale = img.offsetWidth / img.naturalWidth;
const area = document.querySelector('area[shape="rect"]');
const [x1, y1, x2, y2] = area.coords.split(',').map(Number);
area.coords = [
Math.round(x1 * scale),
Math.round(y1 * scale),
Math.round(x2 * scale),
Math.round(y2 * scale)
].join(',');
注意:这段代码必须在 img 的 load 事件之后执行,否则 naturalWidth 可能为 0。
usemap 和 map 的 name 必须严格配对,#不能省
<img usemap="#floorplan"> 中的 #floorplan 必须和 <map name="floorplan"></map> 的 name 完全一致——大小写敏感、不能多空格、不能漏 #。漏掉 #、拼错 name、或把 name 写成 id,热区就完全不激活,而且控制台**零提示**。
稳妥做法是同时声明 id 和 name:
@@##@@ <map id="floorplan" name="floorplan"><area shape="rect" coords="100,50,200,150" href="/room1"></map>
area 必须嵌套在 map 内部,且不能脱离上下文
area 标签不能独立存在,也不接受 id 或 class 直接绑定事件——它只在 map 内部生效。另外,多个 area 重叠时,**先写的优先响应**,后写的会被遮挡,这点容易被忽略。
还有两个硬性要求:
- 每个
area必须带alt属性,否则不满足无障碍标准 - 如果要用 JS 操作热区(比如动态开关),得通过
map.areas集合访问,不能靠document.querySelector('area')直接取(尤其在未加载完成时)
真正麻烦的从来不是写法,而是坐标来源是否可靠、缩放逻辑是否覆盖所有设备、以及 usemap/name 配对有没有手抖漏掉 #——这些地方一错,整个热区就静默挂掉。

前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











