获取鼠标的位置/坐标
程序员文章站
2022-05-13 16:29:38
...
使用javascript 如何获取鼠标的位置呢?
获取光标的位置 获取鼠标坐标
先看效果
核心方法:
/*** * 返回鼠标的坐标 * @param e * @returns {{x: (Number|pageX|*), y: (Number|pageY|*)}} */ var getCoordInDocument = function(e) { e = e || window.event; var x = e.pageX || (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)); var y= e.pageY || (e.clientY + (document.documentElement.scrollTop || document.body.scrollTop)); return {'x':x,'y':y}; }
页面代码:
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="svn_js/common_util.js"></script> <script type="text/javascript"> var getCoordInDocumentExample = function(){ var coords = document.getElementById("coordAreas"); coords.onmousemove = function(e){ var pointer = getCoordInDocument(e); var coord = document.getElementById("coord"); coord.innerHTML = "X,Y=("+pointer.x+", "+pointer.y+")"; } } window.onload = function(){ getCoordInDocumentExample(); }; </script> </head> <body> <div id="coordAreas" style="width:500px;height:200px;background:#F2F1D7;border:2px solid #9C89CB;border-radius: 5px 5px 5px 5px;"> 请在此移动鼠标。 </div> <br /> <div id="coord" style="width:500px;border:2px solid #9C89CB;border-radius: 5px 5px 5px 5px;"> </div> </body> </html>