实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>获取鼠标坐标</title> <style type="text/css"> *{margin:0;padding: 0} .box{margin:50px auto;width:500px;height:500px;} #main{ margin:100px auto; width:100%; height:100%; border: 2px solid red; } p{margin:50px auto;width:500px;height:40px;line-height: 40px;border: 2px solid red;} </style> </head> <body> <div class="box"> <div id='main'></div> <br> <p>当前鼠标位置<span id='info'>(0,0)</span></p> </div> <script type="text/javascript"> window.onload=function(){ var divObj=document.getElementById('main'); divObj.onmousemove=function(event){ var e=event||window.event; //获取鼠标坐标 var m_x=e.clientX; var m_y=e.clientY; var d_x=this.offsetLeft; var d_y=this.offsetTop; var x=m_x-d_x; var y=m_y-d_y; info.innerHTML='('+x+','+y+')'; } } </script> </body> </html>
运行实例 »
点击 "运行实例" 按钮查看在线实例
心得:
实现的过程中出了BUG,总是不能显示数据
发现了window.onload=function()后面的花括号没有成对,导致了BUG