javascript 获取鼠标相对于文档的坐标
这个功能有兼容性问题,因为ie和标准模式的下的获取坐标的方法有区别,比如,标准模式才pageX,pageY获取到的是相对文档的坐标,但是ie的clientX,clientY获取到的是相对与当前屏幕的坐标,所以要通过其他的,scrollTop和scrollLeft ,clientLeft和clientTop做算法获取到相对文档的坐标
代码很简单的
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>坐标</title> <meta name="description" content=""> <meta name="keywords" content=""> <link href="" rel="stylesheet"> </head> <body style="height:3000px;"> </body> </html> <script> window.onload = function(){ function movexy(e){ //判断是否是标准模式 if(e.pageX || e.pageY){ return { x:e.pageX, y:e.pageY } }else{ //ie return{ x:e.clientX + document.body.scrollLeft - document.body.clientLeft, y:e.clientY + document.body.scrollTop - document.body.clientTop } } } document.onmousemove = function(e){ var m = movexy(e); console.log('x:'+m.x+' '+'y:'+m.y); } } </script>
javascript:
<script> window.onload = function(){ function movexy(e){ //判断是否是标准模式 if(e.pageX || e.pageY){ return { x:e.pageX, y:e.pageY } }else{ //ie return{ x:e.clientX + document.body.scrollLeft - document.body.clientLeft, y:e.clientY + document.body.scrollTop - document.body.clientTop } } } document.onmousemove = function(e){ var m = movexy(e); console.log('x:'+m.x+' '+'y:'+m.y); } } </script>