简体   繁体   中英

How to get the cursor position within a centered div?

I was making a drawing app and I had to center it.

To detect the cursor position I used

$('#drawbox').mousedown(function(e){
    paint = true;

    var mouseX = e.pageX - this.offsetLeft;
    var mouseY = e.pageY - this.offsetTop;

    addClick(e.pageX-this.offsetLeft, e.pageY-this.offsetTop);
    redraw();
});

the drawbox div is wrapped in a centering div with the following style

position:relative;
margin:auto;
text=align:center;

It resulted in my drawings being out of bounds, for some reasons it was working fine without the centering wrapper div. thanks you for your help

Here is a fiddle for demo

https://jsfiddle.net/ok0ohbxj/

Refering to the fiddle you posted in a comment to your question, the problem is your usage of offsetTop :

The HTMLElement.offsetTop read-only property returns the distance of the current element relative to the top of the offsetParent node.

In your case, the offsetParent node is the wrapping container .centerHelper not your document.

Since you're already using jQuery, i suggest to go with $('drawbox').offset() instead, which returns the offset relative to the document:

$('#drawbox').mousedown(function(e){
    paint = true;

    var mouseX = e.pageX - $('#drawbox').offset().left;
    var mouseY = e.pageY - $('#drawbox').offset().top;
    addClick(mouseX, mouseY);
    redraw();
});

$('#drawbox').mousemove(function(e){
    if (paint){
        var mouseX = e.pageX - $('#drawbox').offset().left;
        var mouseY = e.pageY - $('#drawbox').offset().top;
        addClick(mouseX,mouseY, true);
        redraw();
    }
});

And a fiddle for you to try out: https://jsfiddle.net/6gwnexjL/

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