简体   繁体   中英

Accurate jQuery x y mouse click on image

I have a div with a background image - the div is set to the exact size of the image and my pointer is set to a crosshair over the div.

I want to mark each click with its x and y positions in the div over the image background. This I can do but the mark on the div is always lower and to the left of the actual cursor why is this?

function showClick(x,y)
{
    $('.clickable').append('<span id="'+x+y+'_span" style="position: absolute;top:'+y+'px;left:'+x+'px;" class="red">+</span>');
}

$('.clickable').bind('click', function (ev) {
    var $div = $(ev.target);
    var offset = $div.offset();
    var xMargin = ($div.outerWidth() - $div.width()) / 2;
    var yMargin = ($div.outerHeight() - $div.height()) / 2;
    var x = (ev.pageX + xMargin) - offset.left;
    var y = (ev.pageY + yMargin) - offset.top;

    showClick(x,y);

});

working example: https://jsfiddle.net/b94ypmae/3/

You are not taking into account the size of the span (and the character inside it).

Your code is working properly, in that a span is being placed in your div at the position of your cursor, but that position is based on the upper left corner

If you put a border around your span you can see it is a perfect alignment of your upper left corner: JSFiddle showing border

You could fix this by taking into account the size of the placed span(if you know it will always be the same you could hard code it as well). Here's an example of getting the size of the placed span and moving it by half it's width and height: Fixed JSFiddle

var placedSpan = $("#" + x + y + "_span");
var width = placedSpan.width();
var height = placedSpan.height();
placedSpan.css('left', x - width / 2 + 'px');
placedSpan.css('top', y - height / 2 + 'px');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM