html 标签的 coords 属性不支持百分比,仅接受像素整数;响应式需用 js 动态按 naturalwidth/height 与 offsetwidth/height 缩放坐标;更优解是改用 svg,其原生支持百分比、viewbox 和媒体查询。

coords 属性的百分比根本不存在
HTML <area> 标签的 coords 属性不支持百分比值,只接受像素整数(如 "10,20,100,120")。浏览器会直接忽略带 % 的坐标(例如 "10%,20%,100%,120%"),导致热点失效或定位错乱。这不是兼容性问题,而是规范限制——coords 始终相对于图像原始尺寸(width/height 属性或 intrinsic 尺寸)计算。
响应式 area 热点必须靠 JS 动态重算
当 <img> 使用 max-width: 100% 或被缩放时,原图尺寸与渲染尺寸不一致,硬编码的 coords 就会偏移。解决路径只有一条:监听窗口/图片尺寸变化,按比例缩放坐标值。
- 先用
img.naturalWidth和img.naturalHeight获取原始尺寸 - 再用
img.offsetWidth/img.offsetHeight获取当前渲染尺寸 - 计算缩放比:
scaleX = offsetWidth / naturalWidth,scaleY = offsetHeight / naturalHeight - 对每个
<area>的coords字符串做解析 → 数值映射 → 缩放 → 重新赋值
示例关键逻辑:
const areas = document.querySelectorAll('map[name="mymap"] area');
areas.forEach(area => {
const coords = area.coords.split(',').map(Number);
const scaled = coords.map((v, i) => Math.round(i % 2 === 0 ? v * scaleX : v * scaleY));
area.coords = scaled.join(',');
});
更稳的方案:用 SVG 替代 image map
原生 <area> 响应式改造成本高、易出错,尤其涉及旋转、缩放、高清屏(dpr > 1)时。SVG 的 <use></use>、<rect></rect>、<circle></circle> 等元素天然支持百分比、viewBox 缩放和 CSS 媒体查询。
- 把图像作为
<image></image>嵌入 SVG,设置preserveAspectRatio="xMidYMid meet" - 热点用
<rect x="10%" y="20%" width="20%" height="15%"></rect>直接写百分比 - 整个 SVG 设为
width: 100%; height: auto;,所有坐标自动响应 - 点击事件绑定在 SVG 元素上,用
event.target区分区域
容易被忽略的两个细节
一是 img 的 width/height 属性未设置时,naturalWidth/Height 虽可读,但 CSS 缩放可能受外层容器约束,需确保获取 offsetWidth/Height 时图片已 layout 完成(避免在 DOMContentLoaded 中立即执行,改用 img.onload 或 ResizeObserver);二是多边形 coords(如 "50,10,90,40,80,90,20,90,10,40")必须严格保持偶数个数值,缩放时逐点处理,顺序错一位整个形状就翻转。











