2012-07-21 55 views
0

可能重複:
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

回答

0

使用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

0

你可以做這樣的事情來獲得x和y,其中 'theimage' 是你的形象

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


});