确定使用 JavaScript(或 jQuery)单击了地图 (imageMap) 中的哪个区域

Determine which Area in a Map (imageMap) was clicked using JavaScript (or jQuery)

本文关键字:imageMap 地图 区域 单击 JavaScript jQuery      更新时间:2023-09-26

我正在为客户端编写一个模型(使用HTML,JS/jQuery)和CSS,其中涉及具有单个图像(接口)并应用了Map。出于某种原因,我不会解释当单击某个区域时执行一个动作,其中包括动画,然后更改图像src(所以它看起来像是在界面之间移动),然后我对图像应用不同的图像映射(也许我应该说<img>标签)

客户要求这个,我知道这看起来很疯狂,但我没有任何模型工具来执行动画等,等等......

我注意到了一种模式,我可以重构我的代码,以便更容易扩展和维护。但是我想知道,假设我有以下 HTML:

<img src="claas_ipad3.jpg" USEMAP="#claas_ipad3" width="1130" height="871" alt="" border="0" id="mainPage">
    <map name="claas_ipad3">
      <area shape="rect" coords="181,249,255,341" href=""  alt="" id="Contacts">
      <area shape="rect" coords="345,251,454,341" href=""  alt="" id="Appointments">
      <area shape="rect" coords="533,256,576,311" href=""  alt="" id="Maps">
      <area shape="rect" coords="686,255,785,344" href=""  alt="" id="Tasks">
      <area shape="rect" coords="835,246,973,348" href=""  alt="" id="Products">
      <area shape="rect" coords="176,412,278,513" href=""  alt="" id="Reports">
      <area shape="rect" coords="330,411,457,513" href=""  alt="" id="PriceTable">
      <area shape="rect" coords="502,399,637,518" href=""  alt="" id="SalesCycle">
      <area shape="rect" coords="677,398,808,519" href=""  alt="" id="MetaData">
      <area shape="rect" coords="844,408,970,510" href=""  alt="" id="Settings">
      <area shape="rect" coords="173,545,283,662" href=""  alt="" id="Vids">
      <area shape="rect" coords="328,558,461,652" href=""  alt="" id="Web">
      <area shape="rect" coords="491,559,626,666" href=""  alt="" id="Files">
    </map>

我是否可以使用 JavaScript 或 jQuery 确定某个区域是否被点击?然后我可以识别 ID 并执行正确的操作。我目前拥有的是许多不同的条件,例如...

 $("#Contacts").click(function(event){
            event.preventDefault();
            // okay lets show the contacts interface
            $("#mainPage").fadeOut(300, function(){
                $(this).attr('src','claas_ipad3_1.jpg').bind('onreadystatechange load', function(){
                    if (this.complete){
                        $(this).fadeIn(300);
                        $(this).attr('USEMAP','#claas_ipad_1');
                    }
                    });
                });
            });

但是,如果我知道单击了哪个区域(通过确定 id),我可以将数组值应用于通用函数,而不是专门绑定到地图区域。

我想我可以确定点击的内容的 id,如下所示:

$(this).live('click', function () {
    alert($(this).attr('id')); 
});

但是这会影响我的整个页面,这不是问题,但我知道它不起作用。

对不起,如果我没有很好地解释自己或我的措辞很差。如果需要,我可以扩展或改写。

谢谢

更新

我已经解决了这个问题,如果我使用以下方法将 ID 应用于地图,将返回 ID

 $("#Map1 area").click( function () {
        alert($(this).attr('id')); // this
    });

有不同的方法。我想最简单的是这个:

$("map[name=claas_ipad3] area").live('click', function () {
    alert($(this).attr('id')); 
});

请注意,从 jQuery 1.7 开始,.live() 方法已被弃用,您应该使用 .on() 来附加事件处理程序:

$("map[name=claas_ipad3] area").on('click', function () {
    alert($(this).attr('id')); 
});