Correction status:Uncorrected
Teacher's comments:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>实时获取鼠标在div中的-相对位置坐标</title> <style type="text/css"> #main{ width: 500px;height:400px; margin: 100px auto 20px; border: 2px solid red; } p{ width: 500px;height: 50px; margin: 0 auto; border: 2px solid green; line-height: 50px; } </style> </head> <body> <div id='main'></div> <p>坐标为:<b id='show'>(0,0)</b></p> <script type="text/javascript"> window.onload=function(){ var divobj=document.getElementById('main'); var showobj=document.getElementById('show'); divobj.onmousemove =function(event){ var e=event || window.event; //获取鼠标坐标 var m_x=e.clientX; var m_y=e.clientY; //获取div坐标 var d_x=this.offsetLeft; //offsetLeft:Html元素相对于文档的x轴位置 var d_y=this.offsetTop; //Html元素相对于文档的y轴位置 var x=m_x-d_x; var y=m_y-d_y; showobj.innerHTML='('+x+','+y+')'; } } </script> </body> </html>
点击 "运行实例" 按钮查看在线实例