单击此图像的地图区域时获取img标记ID

时间:2012-11-26 19:37:41

标签: javascript html image shape area

我有一些像这样的地图区域的图像

image area

我点击区域区域内时需要获取图片ID 我可以用js做自定义区域功能实现吗?

UPD sandbox

UPD2 发现第二个,其他问题。 第一个区域区域(红色),第二个图像覆盖不可点击,z-index覆盖区域不工作。

image problem

最终更新
我写了一些小的自定义函数来映射一些对象 也许它会帮助某人:
jsFiddle

3 个答案:

答案 0 :(得分:1)

就像假设你可以使用jQuery一样:

<img id="planetsimg" src="planets.gif" width="145" height="126" alt="Planets" usemap="#planetmap">

<map name="planetmap">
  <area shape="rect" coords="0,0,82,126" href="sun.htm" onclick="clicked(this)" alt="Sun" image-id="planetsimg">
  <area shape="circle" coords="90,58,3" href="mercur.htm" onclick="clicked(this)" alt="Mercury" image-id="planetsimg">
  <area shape="circle" coords="124,58,8" href="venus.htm" onclick="clicked(this)" alt="Venus" image-id="planetsimg">
</map>

<script>
function clicked(map) {
    var image = $('#' + $(map).attr('image-id'));
    alert('img ' + image + ' clicked map ' + $(map).attr('href'));

    return false; // Prevents href from opening normally. Return true if you want the link to open
</script>

答案 1 :(得分:1)

我希望这就是你要找的东西

JS小提琴示例:http://jsfiddle.net/g5Dy3/44/

<强> HTML

<img id="dotted" src="image1.jpg" usemap="#ballmap" alt="sample" />
<img id="solid" src="image2" usemap="#ballmap2" alt="sample" />

<map name="ballmap">
    <area shape="circle" coords="210,120,90" href="#" alt="dotted ball" title="dotted ball" onclick="clickedMe(this);">
</map>
<map name="ballmap2">
    <area shape="circle" coords="126,90,70" href="#" alt="solid ball" title="solid ball" onclick="clickedMe(this);">
</map> 

<强> JS

function clickedMe(item) {
    var mapName;
    mapName = $(item).parent().attr('name');
    $('img').each(function(){
        if($(this).attr('usemap') == '#'+mapName){
            alert($(this).attr('id'));            
        }       
    });
}

答案 2 :(得分:0)

只需将点击处理程序添加到地图的区域(图像),而不是地图本身

如果你使用的是jQuery,你可以这样做:

$('map').find('area').each(function() {
  $(this).on('click',... 
});
相关问题