Copy codeThe Code is as follows:
<HEAD>
<TITLE> Get DIV relative coordinates in JS </TITLE>
<Script type = "text/javascript"> <! --
Function getX (obj ){
Var parObj = obj;
Var left = obj. offsetLeft;
While (parObj = parObj. offsetParent ){
Left + = parObj. offsetLeft;
}
Return left;
}
Function getY (obj ){
Var parObj = obj;
Var top = obj. offsetTop;
While (parObj = parObj. offsetParent ){
Top + = parObj. offsetTop;
}
Return top;
}
Function DisplayCoord (event ){
Var top, left, oDiv;
ODiv = document. getElementById ("demo ");
Top = getY (oDiv );
Left = getX (oDiv );
Document. getElementById ("mp_x"). innerHTML = (event.clientx-left?document.doc umentElement. scrollLeft)-2 + "px ";
Document. getElementById ("mp_y"). innerHTML = (event.clienty-topw.document.doc umentElement. scrollTop)-2 + "px ";
}
// --> </Script>
</HEAD>
<BODY style = "margin: 40px;" mce_style = "margin: 40px;">
<Div style = "background-color: #000000; color: # 0011FF; width: 300px; height: 300px; position: absolute; top: 80px; left: 90px; margin: 0px; border: 0px; "id =" demo "onmousemove =" DisplayCoord (event) ">
I am a DIV. After testing, there is a 2PX error...
</Div>
The current mouse coordinates are:
X: <span id = "mp_x"> </span>
Y: <span id = "mp_y"> </span>
</Body>
</BODY>
</HTML>
If not, try
Document.doc umentElement. scrollLeft
Replace
Document. body. scrollLeft