开发者

jQuery element coordinates

I have the following code

 $(document).ready(funct开发者_Python百科ion(){
        $('img').mousedown(function(event) {
            $('p').text('Mouse Clicked x =' + event.screenX + ' Y = ' + event.screenY);
        });
    });

Which nicely finds the screen co ordinates of the cursor if they click on the image, but what I would actually like is the co-ordinates within the image they clicked (1,1 for top left, regardless of the images location in the page) but I can't see anyway of doing this other than to place the image in it's own page and use pageX/pageY ... or am I looking at this wrong


The following code works so far as I can tell:

$('img').mousedown(function(e) {
    var offset = $(this).offset(),
        imgLeft = e.pageX - offset.left,
        imgTop = e.pageY - offset.top;

    $('p').text('Mouse clicked x = ' + imgLeft + ' Y = ' + imgTop);
});

See jsFiddle.


You don't want screenX and screenY, you want pageX and pageY. You can then easily subtract the image's position (retrieved via offset) to determine where within the image was clicked:

$('img').click(function(event) {
  var imgPos;

  imgPos = $(this).offset();
  display('Mouse click at ' + event.pageX + 'x' + event.pageY);
  display('Image at ' + imgPos.left + 'x' + imgPos.top);
  display(
    'Delta within image: ' +
    (event.pageX - imgPos.left) +
    'x' +
    (event.pageY - imgPos.top)
  );
});

function display(msg) {
  $("<p/>").html(msg).appendTo(document.body);
}

Live example


Have you tried subtracting the offsetLeft and offsetTop of the image (and its parents) from your numbers?

You may need to while through the offsetParents to get all of the offsets.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜