You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现带鼠标悬停高亮效果的响应式Image Map?

实现带悬停高亮的响应式Image Map(纯原生方案)

核心思路

原生<area>元素无法直接设置高亮样式,因此我们采用SVG层叠加在图片上方的方式实现高亮效果,同时利用SVG的特性自动适配响应式缩放,再通过JavaScript绑定鼠标事件完成交互,全程无需依赖jQuery插件。

完整实现步骤

1. 调整HTML结构

保留原有<map>和<area>保证点击跳转功能,新增SVG容器放置高亮区域:

<section>
  <div class="image-map-container">
    <!-- 响应式图片 -->
    <img id="target-image" src="https://www.linkpicture.com/q/A1C-PBOBiFL._AC_SL1500.jpg" 
         orgWidth="1396" orgHeight="940" usemap="#image-maps" alt="" />
    <!-- SVG高亮层 -->
    <svg id="highlight-svg" viewBox="0 0 1396 940" preserveAspectRatio="xMidYMid slice">
      <!-- 与多边形area对应的高亮路径 -->
      <polygon id="area-highlight" points="477,473 499,484 509,501 539,513 561,522 551,552 538,590 512,597 478,593 452,600 437,596 428,581 418,571 394,545 384,521 389,501 397,477 401,462 412,449 443,455" 
               style="fill:rgba(255,255,0,0.3);opacity:0;transition:opacity 0.2s;" />
    </svg>
    <!-- 原始映射 -->
    <map name="image-maps" id="image-maps">
      <area shape="rect" coords="1394,938,1396,940" alt="Image Map" style="outline:none;" title="Image Map" href="brazil.html" />
      <area shape="poly" coords="477,473,499,484,509,501,539,513,561,522,551,552,538,590,512,597,478,593,452,600,437,596,428,581,418,571,394,545,384,521,389,501,397,477,401,462,412,449,443,455" 
            style="outline:none;" target="_self" />
    </map>
  </div>
</section>

2. CSS样式配置

设置容器相对定位让SVG与图片重叠,保证响应式缩放:

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  min-height: 100vh;
}

.image-map-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
}

#target-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

#highlight-svg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none; /* 避免干扰下方图片和area的点击 */
}

#area-highlight {
  cursor: pointer;
  pointer-events: auto; /* 单独让高亮区域响应鼠标事件 */
}

3. JavaScript交互逻辑

绑定鼠标事件控制高亮显示,利用SVG特性自动适配响应式:

const polyArea = document.querySelector('area[shape="poly"]');
const highlight = document.getElementById('area-highlight');

// 鼠标悬停显示高亮
polyArea.addEventListener('mouseover', () => {
  highlight.style.opacity = '1';
});

// 鼠标离开隐藏高亮
polyArea.addEventListener('mouseout', () => {
  highlight.style.opacity = '0';
});

// 响应式适配:SVG的viewBox已绑定原始尺寸,容器缩放时自动适配,无需手动计算坐标
window.addEventListener('resize', () => {});

关键说明

  • SVG的viewBox绑定图片原始尺寸,配合preserveAspectRatio属性,能自动跟随容器缩放,彻底解决响应式坐标匹配问题。
  • 通过pointer-events属性精准控制交互层级,既保留原始<area>的跳转功能,又能让高亮区域响应鼠标事件。
  • 高亮样式通过SVG的fill和opacity实现,配合过渡动画让效果更平滑。

内容的提问来源于stack exchange,提问作者Christian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 22:43:21