如何从身体上的 onClick 事件获取鼠标单击的绝对位置?
我试图获取鼠标点击相对于浏览器/正文的绝对位置(顶部和左侧),不是正文中的任何父元素.
I am trying to get the absolute position (top and left) of a mouse click relative to the browser/body, not any parent elements within the body.
我有一个绑定到正文的侦听器,但是 e.pageX 和 e.pageY 给了我相对于 div 的位置.
I have a listener bound to the body, but e.pageX and e.pageY are giving me the position relative to a div.
请注意,我可以利用 jQuery 和 YUI 函数.
Note that I can leverage jQuery and YUI functions.
当前无法正常工作的代码:
//getting the position
function _handleClick(e) {
var data = { absX: e.pageX, absY: e.pageY};
_logClickData(data);
}
//binding the function
var methods = {
init: function () {
$("body").click(_handleClick);
}
};
根据这个 (http://docs.jquery.com/Tutorials:Mouse_Position),那些应该给你绝对位置.offsetX/Y
给你相对位置.
According to this (http://docs.jquery.com/Tutorials:Mouse_Position), those should give you absolute positions. offsetX/Y
gives you the relative position.
编辑 2013 年 11 月:原始的鼠标位置"链接似乎已损坏,但 pageX
的文档包含一个使用 jQuery pageX
/Y
的示例.关于offset
方法的页面也包含相关示例.
Edit November 2013: the original "Mouse Position" link seems to be broken, but the documentation for pageX
contains an example that utilizes jQuery pageX
/Y
. The page about the offset
method also contains relevant examples.