2011-07-19 49 views
0

我想捕获图像上的单击事件(这是一个div的背景图像)。我有以下代码:图像的javascript偏移值

findPos:function(obj) { 
      var pos = new Object(); 
      pos.x = pos.y = 0;   
      if (obj.offsetParent) 
      { 
      do 
      { 
       pos.x += obj.offsetLeft; 
       pos.y += obj.offsetTop; 
      } while (obj = obj.offsetParent); 
      } 
      return pos; 
     } 

上面的代码返回相同的div值。但是我想获得div内的坐标。

+0

你想获得div内的鼠标坐标或背景图像位置吗? –

+0

使用css居中的div的相对鼠标坐标 – gk1

回答

1

您正在寻找这样的事情:

http://jsbin.com/ogarof/

$("#special").click(function(e){ 

    var x = e.pageX - this.offsetLeft; 
    var y = e.pageY - this.offsetTop; 

     $('#status2').html(x +', '+ y); 
    }); 

<html> 
    <head> 
    <script class="jsbin" 
      src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"> 
    </script> 
    </head> 
    <body>  
    <h2 id="status2"> 
    0, 0 
    </h2> 
    <div style="width: 100px; height: 100px; background:#ccc;" id="special"> 
    Click me anywhere! 
    </div> 
    </body> 
</html> 
+0

这是一个很好的答案,只要@ gk1不反对使用jQuery –

+0

对于这样的简短代码片段,只需将它们添加到答案中即可。外部“垃圾桶”往往会遭受链接腐烂。 – Kev

0

只需找到的div坐标,就像你在做什么,并从鼠标坐标相减点击事件。