javascript获取鼠标点击位置的坐标兼容写法
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>获取鼠标点击位置</title> 6 <script>
//考虑浏览器滚动条 7 function getMousePos(event) { 8 var e = event || window.event; 9 var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft; 10 var scrollY = document.documentElement.scrollTop || document.body.scrollTop; 11 12 var x = e.pageX || e.clientX + scrollX; 13 var y = e.pageX || e.clientY + scrollY; 14 15 return { 16 'x': x, 17 'y': y 18 }; 19 } 20 function mouseMove(event){ 21 var e = event || window.event; 22 var mosePos = getMousePos(event); 23 document.getElementById("txtX").value = mosePos.x; 24 document.getElementById("txtY").value = mosePos.y; 25 }
//鼠标按下时的坐标 26 document.onmousedown = mouseMove; 27 28 </script> 29 </head> 30 <body> 31 x:<input type="text" id="txtX"> 32 y:<input type="text" id="txtY"> 33 </body> 34 </html>