开发者

How can I calculate the co-ordinates of the mouse position in relation to a pre-defined point using Javascript / jQuery

What I am trying to achieve sounds,开发者_如何学Python and probably is quite simple.

A point, lets say the absolute center of the browser is the marker.

I know how to calculate the mouse position in relation to a bounding box or the document window, but how can I calculate it, in a sort of grid system from the marker?

So, for example, the mouse is to the left of the marker and i am returned minus figures for the x axis, if it's below the point, I will receive minus figures for both the x and y axis, and then of course the opposite.

Thank you


CenterPoint - MousePosition = MousePosition relative to center point.

If x is less than 0 it's to the left. If y is less than 0 it's beneath it.

So if x is less than 0 and y is greater than 0 the point is in the "upper left"


Live Demo

Basically you get the mouse coordinates and subtract the current elements position, minus the width and height/2, to get its center point.

$(document).mousemove(function(e){
    var offset = $("#offsetElement").offset(),
        offWidth = $("#offsetElement").width()/2,
        offHeight = $("#offsetElement").height()/2,
        offX = e.pageX - offset.left - offWidth ,
        offY = e.pageY - offset.top - offHeight;

    $('#coords').html(offX  + ', ' +  offY);
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜