核心思想:
1、复杂版本:鼠标pageX、pageY的值减去盒子距离顶端的offsetLeft、offsetTop值就是鼠标在盒子中的坐标
2、简单版本:offsetX、offsetY就可获取鼠标相对于事件触发对象的坐标,以事件触发对象左上角为基准点
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { padding: 0; margin: 0; } div { width: 400px; height: 400px; background-color: #ccc; margin: 150px auto; font: 600 17px/400px "simsun"; text-align: center; } span { color: red; } </style> </head> <body> <div> 鼠标在盒子中的坐标X:000 Y:000 </div> <script> var divEle = document.getElementsByTagName("div")[0]; divEle.onmousemove = function (ev) { ev = ev || window.event; var pageX = ev.pageX || scroll().left + ev.clientX; var pageY = ev.pageY || scroll().top + ev.clientY; var x = pageX - divEle.offsetLeft; var y = pageY - divEle.offsetTop; divEle.innerHTML = "鼠标在盒子中的坐标X:" + "<span>" + x + "</span>" + " Y:" + "<span>" + y + "</span>"; } function scroll() { return { "top": window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop, "left": window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft }; } </script> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { padding: 0; margin: 0; } div { width: 400px; height: 400px; background-color: #ccc; margin: 150px auto; font: 600 17px/400px "simsun"; text-align: center; } span { color: red; } </style> </head> <body> <div> 鼠标在盒子中的坐标X:000 Y:000 </div> <script> var divEle = document.getElementsByTagName("div")[0]; divEle.onmousemove = function (ev) { ev = ev || window.event; var x = ev.offsetX; var y = ev.offsetY; divEle.innerHTML = "鼠标在盒子中的坐标X:" + "<span>" + x + "</span>" + " Y:" + "<span>" + y + "</span>"; } </script> </body> </html>