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.
I have a listener bound to the body, but e.pageX and e.pageY are giving me the position relative to a div.
Note that I can leverage jQuery and YUI functions.
Code that currently does not work correctly:
//getting the position
function _handleClick(e) {
var data = { absX: e.pageX, absY: e.pageY};
_logCli开发者_如何转开发ckData(data);
}
//binding the function
var methods = {
init: function () {
$("body").click(_handleClick);
}
};
The commenter is correct. pageX and pageY give you the mouse position relative to the entire document not its parent div. But if you're interested you can get the position relative to the document from the position relative to a div.
Get the position of the parent div relative to the body, then add the two values.
x = parentdiv.style.left + e.pageX;
y = parentdiv.style.top + e.pageY;
(0,0)
_____________________
|
|
| __________
|----100----| |
| |---60---* |
| |__________|
|
|
* = Mouse Pointer
I made the diagram because it was fun. Not because I felt you needed one!!
Also, for the above to work you may need to parseInt.
According to this (http://docs.jquery.com/Tutorials:Mouse_Position), those should give you absolute positions. offsetX/Y
gives you the relative position.
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.
If I understood your question well this would be the solution
$("body").click(function(e){
var parentOffset = $(this).offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
window.alert(relX);
window.alert(relY);
});
I guess you can use window.pageXOffset
, window.pageYOffset
property
document.body.addEventListener('click',(e)=>{
console.log(e.clientX + window.pageXOffset, event.clientY + window.pageYOffset)
}
)
The solution, hinted at by @Mrchief's link of http://docs.jquery.com/Tutorials:Mouse_Position, was to bind to the document and not the body element.
//binding the function
var methods = {
init: function () {
$(document).click(_handleClick);
}
};
精彩评论