计算单击了偏移图像的

问题描述:

可能重复:
getting the X/Y coordinates of a mouse click on an image with jQuery计算单击了偏移图像的

我要计算一个图像的点击位置,可以说,这将是一个例子:

enter image description here

如果我在某处点击它,我想要要在图像上显示点击区域的X/Y位置的警报,图像上有像素,所以它应该显示x像素偏移量和y像素偏移量。

这可能与JavaScript有关吗?任何例子,将不胜感激。

+0

你可以使用jQuery的id? – 2012-07-21 11:11:14

+0

@BaliBalo当然可以。 – Scott 2012-07-21 11:12:17

+0

您是否尝试http://www.google.com/search?q=image+coordinates+on+click – mplungjan 2012-07-21 11:17:22

使用JQuery,使用要减去的元素的偏移量的事件的pageX和pageY值。

http://jsfiddle.net/BramVanroy/D63KS/1/

$(document).ready(function(){ 
    $('img').mousedown(function(e){ 
     var offset = { 
      x: e.pageX - $(this).offset().left, 
      y: e.pageY - $(this).offset().top 
     } 
      $('#info').html('{'+offset.x+'; '+offset.y+'}'); 
    }); 
});​ 
+0

您可能想要使用有效的图片。 – 2012-07-21 11:17:41

+0

有效的图像?我用他的问题。 – 2012-07-21 11:19:53

+0

好吧,这很奇怪:我没有点击他的形象之前,并右转到你的小提琴。它给我看了一个'破碎的图像',尽管我可以看到他的链接。对不起,评论然后,我的坏。 – 2012-07-21 11:21:31

你可以做这样的事情来获得x和y,其中 'theimage' 是你的形象

$("#theimage").live("click",function(e){ 
e.preventDefault(); 
    var x = e.pageX - $(this).offset().left; 
    var y = e.pageY - $(this).offset().top; 


});