javascript 调整窗口大小时,图像Map顶部的文本不粘滞

qv7cva1a  于 2023-01-19  发布在  Java
关注(0)|答案(2)|浏览(118)

我正在做类似于这个主题的事情:Text on top of image map
我的问题是,标题不完全在圆圈区域的中心,当窗口大小调整时,它们不粘在我的图像上Map的区域,尽管当窗口大小调整时,区域本身总是正确定位的。

<div id="molecule">
      <img src="./images/molecule-total.svg" alt="menu" usemap="#molecule-links">
      <map name="molecule-links">
        <area class="contact" shape="circle" coords="70,100,90" alt="Page1" data-name="Contact">
        <area shape="circle" coords="250,350,150" href="page2.html" alt="Page2" data-name="Home">
      </map>
  </div>
#molecule {
    height: 80vh;
    width: 100vh;
    padding-left: 141px;
    padding-top: 15px;
    position: relative;
}

.map_title {
  position: absolute;
  z-index: 2;
}

img {
  min-height: 80%;
  max-height: 100%;
}

area {
  cursor: pointer;
  outline-color: white;
}
function displayLinksName() {
  const area = document.querySelectorAll("area");
  const map = document.querySelector("map")

  area.forEach(function(area){
    let txt = area.getAttribute('data-name')
    let coor = area.getAttribute('coords');
    let coorA = coor.split(',')
    let left = coorA[0];
    let top = coorA[1];
    let links = document.createElement('div');
    links.classList.add("map-title");
    links.innerHTML =  txt;
    links.style.top = top + 'px';
    links.style.left = left + 'px';
    links.style.position = 'absolute';
    links.style.color = 'red';

    map.append(links);
  })
}

这就像是区域的坐标不遵守CSS属性顶部和左侧的规则一样。有什么变通方法可以让它正常工作吗?

ny6fqffe

ny6fqffe1#

U可以尝试重做javascript,用onresize事件根据图像位置更新文本的位置:

window.addEventListener("resize", updateTextPosition);

function updateTextPosition() {
    var img = document.querySelector("img");
    var imgRect = img.getBoundingClientRect();

    var areas = document.querySelectorAll("area");
    areas.forEach(function(area) {
        var coords = area.getAttribute("coords").split(",");
        var left = coords[0];
        var top = coords[1];

        var text = area.nextElementSibling;

        text.style.left = (imgRect.left + parseInt(left)) + "px";
        text.style.top = (imgRect.top + parseInt(top)) + "px";
    });
}

另外,您可以使用CSS Media查询来调整文本,例如,当窗口宽度小于800时:

@media (max-width: 800px) {
    .map_title {
        top: 50px;
        left: 50px;
    }
}

这将调整文本的位置。

PS:您的javascript中有一个错误,它被写成map-title,而css类被称为map_title

s71maibg

s71maibg2#

我终于找到了最简单的方法来处理任何图像上的Map,而不使用Map或区域标记。https://imagemapper.noc.io/#/并在生成器提供的SVG代码中添加标记。这来自于下面的讨论,其中有很多有趣的方法可以实现这一点:Responsive image map

相关问题