When the mouse is moved over an element, I want to get the mouse coordinates of the cursor relative to the top-left of the element\'s content area (this is the area excludin
using jQuery:
function posRelativeToElement(elem, ev){
var $elem = $(elem),
ePos = $elem.offset(),
mousePos = {x: ev.pageX, y: ev.pageY};
mousePos.x -= ePos.left + parseInt($elem.css('paddingLeft')) + parseInt($elem.css('borderLeftWidth'));
mousePos.y -= ePos.top + parseInt($elem.css('paddingTop')) + parseInt($elem.css('borderTopWidth'));
return mousePos;
};
live example: http://jsfiddle.net/vGKM3/
The root of this is simple: compute the element's position relative to the document. I then drop the top & left padding & border (margin is included with basic positioning calculations). The internal jQuery code for doing this is based on getComputedStyle
and element.currentStyle
. Unfortunately I don't think there is another way...
The core of jQuery's .offset()
function, which gets an element's position relative to document:
if ( "getBoundingClientRect" in document.documentElement ) {
...
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = (win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ),
scrollLeft = (win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft),
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
}else{
// calculate recursively based on .parentNode and computed styles
}
Theoretically, another way to do this would be, using the above positioning code:
position: relative
(or absolute) setposition: absolute; top:0px; left:0px;