因功能需要在图片上点击时,添加自定义的内容。本来想用图片的热区useMap实现,但发现useMap只支持href跳转属性,不能添加自定义的内容。最后通过网上搜索方案,找到如下解决方法。
在点击图片时,通过鼠标点击位置计算点击的坐标,然后在点击的位置添加自定义内容。
示例代码如下:
<!DOCTYPEhtml><htmllang="en"><head><basetarget="_self"><metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/><metahttp-equiv="pragma"content="no-cache"><metahttp-equiv="cache-control"content="no-cache,must-ridate"><metahttp-equiv="expires"content="0"><scriptsrc="./plugins/jquery/jquery.min.js"></script></head><body><divclass="container"><imgid="imageId"src="./images/1.jpg"οnclick="handleClick(event)"></div></body><script>//取图片鼠标点击位置functionhandleClick(e){varxPage=(navigator.appName=='Netscape')?e.pageX:event.x+document.body.scrollLeft;varyPage=(navigator.appName=='Netscape')?e.pageY:event.y+document.body.scrollTop;imgEl=document.getElementById("imageId");img_x=locationLeft(imgEl);img_y=locationTop(imgEl);varxPos=xPage-img_x;varyPos=yPage-img_y;//当前点击位置varhotspot={x:xPos,y:yPos};addHotspot(hotspot);}//找到元素的屏幕位置functionlocationLeft(element){varoffsetTotal=element.offsetLeft;varscrollTotal=0;//element.scrollLeftbutwedontwanttodealwithscrolling-alreadyinpagecoordsif(element.tagName!="BODY"){if(element.offsetParent!=null)returnoffsetTotal+scrollTotal+locationLeft(element.offsetParent);}returnoffsetTotal+scrollTotal;}//找到元素的屏幕位置functionlocationTop(element){varoffsetTotal=element.offsetTop;varscrollTotal=0;//element.scrollTopbutwedontwanttodealwithscrolling-alreadyinpagecoordsif(element.tagName!="BODY"){if(element.offsetParent!=null)returnoffsetTotal+scrollTotal+locationTop(element.offsetParent);}returnoffsetTotal+scrollTotal;}//添加自定义内容functionaddHotspot(hotspot){varx=hotspot.x-12;vary=hotspot.y-12;varsrc='/images/p.png';imgEle='<img'+'src="'+src+'"style="top:'+y+'px;left:'+x+'px;position:absolute;cursor:pointer;"'+')"/>';$('.container').append(imgEle);}</script></html>
效果图如下(定位点为添加的自定义图片):