使用带有自定义HTML元素的图像usemap

Using an image usemap with custom HTML element?

本文关键字:元素 图像 usemap HTML 自定义      更新时间:2024-04-26

在下面的代码示例中,我正在尝试定义我自己的自定义元素<custelem>,我可以对它进行良好的样式设置;然而,我也想给它分配一个图像地图,但我下面的尝试失败了,因为Firefox中的热点上从来没有鼠标悬停:

<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <title>Test</title>
  <script type="text/javascript">
  </script>
  <style type="text/css">
#myone {
  border-color: blue; border-width: 3px; border-style: solid;
  display: block;
  background-color: #AAA;
  /* convert -size 300x300 xc:red red.png */
  background: #EFEFEF url(red.png) 50% 50% no-repeat padding-box border-box scroll;
  background-size: contain;
  width: 300px;
  height: 300px;
}
  </style>
</head>
<body>
  <custelem id="myone" usemap="#TEST"></custelem> <!-- renders the css, but hotspot mouseovers do not work -->
  <!-- <img src="red.png" id="myone" usemap="#TEST"></img> <!-- works in FF, but has to have src attribute for mouseovers -->
  <map id="TEST" name="TEST">
    <area href="javascript:alert('A1')" id="A1" alt="A1 text" shape="rect" coords="50,50,100,100"/>
    <area href="javascript:alert('A2')" id="A2" alt="A2 text" shape="rect" coords="150,150,200,200"/>
  </map>
</body>
</html>

我可以通过css或JS使用带有自定义元素的usemap吗?

这不是一个usemap,而是一个图像map。这就解释了为什么它只适用于图像
但你可以用JS:来解决这个问题

[].forEach.call(document.querySelectorAll("custelem[usemap]"), function(node){
    var img = new Image();
  img.className = "image-map";
  img.useMap = node.getAttribute("usemap");
  img.title = node.getAttribute("title") || "";
  img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWNgYGBgAAAABQABh6FO1AAAAABJRU5ErkJggg=="; // 1x1 transparent png
  node.removeAttribute("usemap");
  node.appendChild(img);
});

和一点点css:

custelem {
  position: relative;
}
custelem img.image-map{
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/u8n6fygz/