如何获取作为相对元素的子元素的 DOM 元素的鼠标位置?

发布于 2024-08-13 15:26:57 字数 54 浏览 1 评论 0原文

如何获取 DOM 元素(即相对元素的子元素)上的鼠标位置 (在 JavaScript 中)?

How to get the mouse position over a DOM element, that is a child of a relative element
(in JavaScript)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赠佳期 2024-08-20 15:26:57

这是当我想要获取元素中的鼠标位置时使用的方法。它返回标准轴(底部 -> 顶部)或网络轴(顶部 -> 底部)中的 y 值。

/*
  Get the position of the mouse event in a standard axis system
  in relation to the given element.

  Standard axis system:
    The origin (0, 0) starts at the bottom-left and increases
    going up for 'y' and right for 'x'.
*/
function GetMousePositionInElement(ev, element)
{
    var offset = element.offset();

    var bottom = offset.top + element.height();

    var x = ev.pageX - offset.left;
    var y = bottom - ev.pageY;

    return { x: x, y: y, y_fromTop: element.height() - y };
}

它需要 jQuery。

Here's the method I use when I want to get the mouse position in an element. It returns the y value in a standard axis (bottom -> top) or in the web axis (top -> bottom).

/*
  Get the position of the mouse event in a standard axis system
  in relation to the given element.

  Standard axis system:
    The origin (0, 0) starts at the bottom-left and increases
    going up for 'y' and right for 'x'.
*/
function GetMousePositionInElement(ev, element)
{
    var offset = element.offset();

    var bottom = offset.top + element.height();

    var x = ev.pageX - offset.left;
    var y = bottom - ev.pageY;

    return { x: x, y: y, y_fromTop: element.height() - y };
}

It requires jQuery.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文