如何从Jquery中元素的中心计算鼠标位置

时间:2022-07-18 20:30:22

I'm trying to find a way of calculating the mouse position from the center of an element.

我试图找到一种从元素中心计算鼠标位置的方法。

I've got as far as e.pageX and e.pageY on the mouse over event, but I can't get my head around calculating its position relative to the elements center.

我已经把e.pageX和e.pageY放在了鼠标上的事件上,但我无法理解它相对于元素中心的位置。

I can't think of the equation

我想不出这个等式

1 个解决方案

#1


2  

You need to first get the object's center point, X & Y (objCenterX & objCenterY in the code, below), then subtract that from the mouse's current coordinates.

您需要首先获取对象的中心点X和Y(下面的代码中的objCenterX&objCenterY),然后从鼠标的当前坐标中减去该值。

This should do it for you:

这应该为你做:

    $("#test").mousemove(function (event) {
        var objLeft = $("#test").offset().left;
        var objTop = $("#test").offset().top;

        var objCenterX = objLeft + $("#test").width() / 2;
        var objCenterY = objTop + $("#test").height() / 2;

        $("#results").text("Left:" + (event.pageX - objCenterX) + ", Top:" + (event.pageY - objCenterY));
    })

#1


2  

You need to first get the object's center point, X & Y (objCenterX & objCenterY in the code, below), then subtract that from the mouse's current coordinates.

您需要首先获取对象的中心点X和Y(下面的代码中的objCenterX&objCenterY),然后从鼠标的当前坐标中减去该值。

This should do it for you:

这应该为你做:

    $("#test").mousemove(function (event) {
        var objLeft = $("#test").offset().left;
        var objTop = $("#test").offset().top;

        var objCenterX = objLeft + $("#test").width() / 2;
        var objCenterY = objTop + $("#test").height() / 2;

        $("#results").text("Left:" + (event.pageX - objCenterX) + ", Top:" + (event.pageY - objCenterY));
    })