Get accurate position for a click on a linked image using jquery

前端 未结 2 365
小鲜肉
小鲜肉 2020-12-16 04:56

I\'m working on an app that allows tagging directly on photos via clicking (like Facebook, flickr, et al). However, I can\'t seem to register the right coordinates for a c

相关标签:
2条回答
  • 2020-12-16 05:34

    My function is:

    function getCoords(target, event)
    {
        var $target = $(target);
        var offset = $target.offset();
        var bordersize = $target.attr('border');
        return {
            x:  (event.pageX - offset.left - bordersize) | 0,
            y:  (event.pageY - offset.top - bordersize) | 0
        }
    }
    

    call:

    $("#image").on('click', function(event){
        var coords = getCoords(this, event);
        console.log('X: ', coords.x);
        console.log('Y: ', coords.y);
    });
    

    Note: used fast float2int.

    0 讨论(0)
  • 2020-12-16 05:37

    for your x and y try using this:

    var x = e.pageX - $(this).offset().left;
    var y = e.pageY - $(this).offset().top;
    

    let me know if that doesn't work

    EDIT: to clarify - you are getting the left and top offset from the dom element directly. the reason i suggest you use the jQuery offset() function is that jQuery is more likely to calculate the correct position cross browser.

    EDIT 2: Can you please try to assign the click event to the image as opposed to the link. I have a sneaking suspicion that the link is reporting its top offset as the bottom of the element it encapsulates...

    0 讨论(0)
提交回复
热议问题