|
Cursor Left = 0px Cursor Top = 0px Element Left = 0px Element Top = 0px Div Cursor Left = 0px
Div Cursor Top = 0px |
Div 1
|
Div 2
|
<HTML>
<HEAD>
<TITLE>Cursor Position Within Div</TITLE>
<script type="text/javascript">
<!--
moz=document.getElementById&&!document.all
function get_el_pos(e,id){
if(!moz){
cursorX=event.clientX
cursorY=event.clientY
}
else{
//cursorX=e.pageX // in relation to page left
//cursorY=e.pageY // in relation to page top
cursorX=e.pageX - document.body.scrollLeft // in relation to window
cursorY=e.pageY - document.body.scrollTop // in relation to window
}
targetID=document.getElementById(id)
currentID=(!moz?event.srcElement.id: e.target.id)
if(currentID==id){
elPosX = targetID.offsetLeft
elPosY = targetID.offsetTop
parent_el = targetID.offsetParent
while (parent_el != null){
elPosX += parent_el.offsetLeft // add left offset of parent
elPosY += parent_el.offsetTop // add top offset of parent
parent_el = parent_el.offsetParent // move up the elements until no more offset parents exist
}
divCurX=(cursorX-elPosX)+document.body.scrollLeft
divCurY=(cursorY-elPosY)+document.body.scrollTop
document.getElementById("cursor_pos").innerHTML = "Cursor Left = "+cursorX+"px<br> Cursor Top = "+cursorY+"px"
document.getElementById("el_pos").innerHTML = "Element Left = "+elPosX+"px<br> Element Top = "+elPosY+"px"
document.getElementById("div_cur_pos").innerHTML = "Div Cursor Left = "+divCurX+"px<br>Div Cursor Top = "+divCurY+"px"
}
}
// -->
</script>
<style>
#div1{
position:absolute;
left:180px;
top:80px;
width:200px;
height:150px;
background-color:#f0ece0;
cursor:hand;
cursor:pointer
}
#div2{
position:absolute;
left:400px;
top:80px;
width:250px;
height:150px;
background-color:#f0ece0;
cursor:hand;
cursor:pointer
}
</style>
</HEAD>
<BODY>
<h1>Cursor Position Within Div</h1>
<div id="cursor_pos">Cursor Left = 0px<br>Cursor Top = 0px</div><br>
<div id="el_pos">Element Left = 0px<br>Element Top = 0px</div><br>
<div id="div_cur_pos">Div Cursor Left = 0px<br>Div Cursor Top = 0px</div>
<div id="div1" onmousemove="get_el_pos(event,this.id)"></div>
<div id="div2" onmousemove="get_el_pos(event,this.id)"></div>
</BODY>
</HTML>