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

时间:2016-04-11 20:30:59

标签: javascript html css

在下面的代码示例中,我尝试定义自己的自定义元素<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>

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

1 个答案:

答案 0 :(得分:1)

它不是一个usemap,它是一个图像映射。这解释了为什么它只适用于图像。
但你可以用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/