2014-01-27 49 views
0

我使用动态生成的图像地图生成图像。我希望用户能够点击地图并通过<area href=属性。在同一图像上使用图像地图和链接

但是,当他们点击背景(即不在任何地图的区域中)时,我希望它们通过背景URL。

所以我的代码看起来是这样的(fiddle):

<a href="fromAnchor.html" target="_blank"> 
    <img src="image.png" usemap="#test" /> 
</a> 

<map name="test" id="test"> 
    <area href="fromMap.html"> 
</map> 

在镀铬/ FX它,因为我期待的作品 - 如果我在area标签的形状点击我得到采取fromMap.html,如果我点击其他地方我被导向到fromAnchor.html

但是,在IE(测试到IE10)点击img,但在area之外什么都不做。它确实在左下角显示URL提示,但不会遵循a标记。

有没有办法解决这个问题?

回答

0

我想出了一个解决方案,但它有点糟糕(所以会很高兴看到更好的答案)。

我的解决方法是动态地添加后备<area>填满整个图像,让点击区区域的秋天外面回来吧:

var msie = /MSIE/.test(navigator.userAgent); 
if (msie) 
{ 
    // Don't do this hack twice 
    $('map[data-iehack!="1"]').each(function() 
    { 
     // First find the image this map applies to 
     var $this = $(this); 
     var name = $this.attr('name'); 
     var $img = $('img[usemap="#' + name + '"]'); 

     // Then find if the image is in an <a> tag 
     var $link = $img.parents('a'); 
     if ($link.length > 0) 
     { 
      // If there is an <a> add an extra <area> that fills the image 
      var wrapLink = $link[0].href; 
      var width = $img.width(); 
      var height = $img.height(); 
      var $fallbackArea = $('<area shape="rect" coords="0,0,' + width + ',' + height + '" />'); 
      $fallbackArea.attr('href', wrapLink); 
      $this.append($fallbackArea); 
     } 

     // Flag this map so we don't add it again 
     $this.attr('data-iehack', '1'); 
    }); 
} 

这个例子是jQuery中,但主要应在其他框架中工作。

必须有一个比这更好的方式 - 这个黑客必须检查浏览器,因为我无法弄清楚如何检测IE的失败。