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

如何使用ImageMap在区域中心添加文本?结合Maphilight.js实现需求

解决Map区域中心添加固定文本的问题

嘿,我来帮你搞定这个需求!你现在的问题是文本没有准确定位到每个区域的中心,对吧?咱们来一步步调整代码,实现页面加载时区域中心显示文本,悬停时触发Maphilight的边框和填充效果的目标:

核心问题分析

你之前的代码用了coords的第一个坐标点(左上角)作为文本位置,这肯定没法让文本居中;另外容器.content没有设置相对定位,导致绝对定位的文本可能会跑偏。

修改后的完整代码

1. 调整后的JavaScript代码

$(document).ready(function(){
  // 初始化Maphilight
  $('.map').maphilight();

  // 给每个area添加中心文本
  $('area').each(function(){
    var txt = $(this).data('name');
    var coor = $(this).attr('coords');
    var coorA = coor.split(',').map(Number); // 转成数字类型方便计算

    // 针对rect形状计算中心坐标(x1,y1,x2,y2)
    if($(this).attr('shape') === 'rect'){
      var centerX = (coorA[0] + coorA[2]) / 2;
      var centerY = (coorA[1] + coorA[3]) / 2;
    }
    // 如果以后有circle/poly形状,可以在这里扩展计算逻辑
    // else if(shape === 'circle') {...}
    // else if(shape === 'poly') {...}

    var $span = $('<span class="map_title">'+txt+'</span>');
    $span.css({
      top: centerY + 'px',
      left: centerX + 'px',
      position: 'absolute',
      transform: 'translate(-50%, -50%)', // 让文本自身居中于坐标点
      zIndex: 10 // 确保文本在地图上方显示
    });
    $span.appendTo('.content');
  })
});

2. 修正后的CSS代码

.content {
  position: relative; /* 关键:让内部绝对定位的元素相对于容器定位 */
  display: inline-block; /* 适配地图的实际尺寸 */
}
.map_title {
  /* 可以自定义文本样式 */
  color: #fff;
  font-size: 14px;
  font-weight: bold;
  text-shadow: 1px 1px 2px #000; /* 增加文本可读性 */
  pointer-events: none; /* 防止文本干扰area的悬停事件 */
}

3. 保持原有的HTML结构不变

<div class="content">
  <img src="ozak.jpg" alt="" class="map" width="2000" height="2000" border="0" usemap="#demo">
</div>
<map name="demo">
  <area id="51" alt="D1" class ="tooltip" title="3+1 150 m² Deniz Manzaralı " href="javascript: alert('Daire 5127 Satılmıştır!')" coords="588,271,816,369" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"F72E06","fillOpacity":0.7}' data-name="Daire1">
  <area alt="" title="" href="javascript: alert('Daire 5287 Satılıktır!')" coords="1251,278,1374,367" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"00BD06","fillOpacity":0.7}' data-name="Daire2">
  <area alt="" title="" href="javascript: alert('Daire 8692 Satılmıştır!')" coords="600,469,807,554" shape="rect" data-maphilight='{"strokeColor":"000000","strokeWidth":5,"fillColor":"F72E06","fillOpacity":0.7}' data-name="Daire3">
</map>

关键修改点说明

  • 坐标计算:针对rect形状,用(x1+x2)/2和(y1+y2)/2计算区域中心,而不是用左上角坐标
  • 文本居中:通过transform: translate(-50%, -50%)让文本自身的中心对齐到区域中心,不管文本长度多少都能完美居中
  • 容器定位:给.content设置position: relative,确保绝对定位的文本不会脱离地图容器
  • 事件不冲突:给.map_title加pointer-events: none,避免文本遮挡area的悬停事件,保证Maphilight效果正常触发

这样修改后,页面加载时每个区域中心都会显示对应的文本,鼠标悬停时会正常触发Maphilight的边框和填充色效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:59:08