遵循模板后Image Mapping仍无法正常工作的问题排查
嘿,我帮你排查了下代码,发现问题大概率出在图片缩放和坐标不匹配上!
你给<img>加了width:50%把图片缩小了,但<area>标签里的coords是按照图片的原始尺寸来定义的,不是缩放后的显示尺寸。这就导致你在页面上看到的可点击区域位置和实际定义的完全对不上,自然点不动啦。
下面给你几个解决办法:
- 方法一:直接去掉图片的
width:50%,让图片以原始尺寸显示。这样你的coords就能准确对应图片上的区域,而且你已经加了居中的CSS,显示效果依然没问题。修改后的代码如下:
<!doctype html> <html> <head> <title>Welcome!</title> <style> img { display: block; margin-left: auto; margin-right: auto; } </style> </head> <body> <img src="bodymap.jpg" usemap="#body"> <map name="body"> <area shape="rect" coords="233,828,485,994" alt="brain" href="brain.html"> </map> </body> </html>
方法二:如果你必须要缩放图片,那就得把
coords里的数值按缩放比例换算。比如你缩放到50%,那每个坐标值都乘以0.5。假设你原来的coords是233,828,485,994,换算后就变成116,414,242,497(可以取整数),这样点击区域就能和缩放后的图片对应上了。方法三:如果需要响应式(比如图片会随窗口大小变化),可以用JS动态计算缩放比例,实时更新
coords。举个简单例子:
<!doctype html> <html> <head> <title>Welcome!</title> <style> img { display: block; margin-left: auto; margin-right: auto; width: 50%; } </style> </head> <body> <img src="bodymap.jpg" usemap="#body" id="bodyImg"> <map name="body"> <area shape="rect" coords="233,828,485,994" alt="brain" href="brain.html" id="brainArea"> </map> <script> const img = document.getElementById('bodyImg'); const area = document.getElementById('brainArea'); // 原始坐标(原图尺寸) const originalCoords = [233, 828, 485, 994]; function updateCoords() { // 计算缩放比例:当前显示宽度 / 原图宽度 const scale = img.clientWidth / img.naturalWidth; // 换算新坐标 const newCoords = originalCoords.map(num => Math.round(num * scale)).join(','); area.coords = newCoords; } // 页面加载时更新一次,窗口大小变化时也更新 window.addEventListener('load', updateCoords); window.addEventListener('resize', updateCoords); </script> </body> </html>
另外也可以检查下图片是否正常加载(打开浏览器开发者工具的网络面板,看bodymap.jpg的请求状态),如果图片加载失败,映射区域也不会生效哦。
内容的提问来源于stack exchange,提问作者Nina
相关产品推荐
相关产品推荐

