开发者

javascript offset value for a image

I am trying to capture a click event on a image (which is a background-image of a div). I have the following code:

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;
        } 
开发者_JAVA技巧

The above code returns the same value for the div. However I want to get the coordinates within the div.


Are you looking for something like this:

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>


Simply find the coordinates of the div, just as you are doing, and subtract them from the mouse coordinates of the click event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜