JQuery开发5-在网页中获取鼠标的三种坐标

在开发过程中。有时候会获取鼠标当前的坐标,主要分为三种,第一种是获取鼠标在屏幕中的坐标,第二种是获取鼠标在客户区中的坐标,第三种是获取鼠标在窗口页面中的坐标。

分别用的方法名称为screenX和screenY,clientX和clientY,pageX和pageY。

属性说明

  • clientX/clientY

    名称 说明 返回
    clientX 返回事件触发时鼠标相对于元素视口 的X坐标 数值
    clientY 返回事件触发时鼠标相对于元素视口 的Y坐标 数值

    这里的元素视口实际上代指就是浏览器,clientX是鼠标距离浏览器左边框的距离,clientY是鼠标距离浏览器上边框的距离。当鼠标停留在页面某个位置时,滚动鼠标滚动条,坐标会随着鼠标滚动条的改变而改变。

  • screenX/screenY

    名称 说明 返回
    screenX 返回事件触发时鼠标相对于屏幕 的X坐标 数值
    screenY 返回事件触发时鼠标相对于屏幕 的Y坐标 数值

    顾名思义,screenX是鼠标距离显示器屏幕左边框的距离,screenY是鼠标距离显示器屏幕上边框的距离。

  • pageX/pageY

    名称 说明 返回
    pageX 返回事件触发时鼠标相对于文档 的X坐标 数值
    pageY 返回事件触发时鼠标相对于文档 的Y坐标 数值
     

    如果鼠标停留在网页中的某个位置,滚动鼠标滚动条,pageY不会因为鼠标滚动的滚动而改变。

  • 参考代码如下
  • Java代码   收藏代码
    1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
    2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
    3. <html>  
    4. <head>  
    5. <script language="javascript"  
    6.     src="${pageContext.request.contextPath}/script/jquery.js"></script>  
    7. <script type="text/javascript">  
    8.     $(document).ready(function() {  
    9.         $(document).mousemove(function(e) {  
    10.             getScreenCoordinates(e);//获取鼠标在屏幕中的坐标  
    11.             getClientCoordinates(e);//获取鼠标在窗口客户区中的坐标,会随着滚动条的滚动而变化  
    12.             getPageCoordinates(e);//获取鼠标当前页面区域中的坐标,不会随滚动条滚动而变化  
    13.         });  
    14.         function getScreenCoordinates(e) {  
    15.             x1 = e.screenX;  
    16.             y1 = e.screenY;  
    17.             $(".sp1").text("X1:" + x1 + ",Y1:" + y1);  
    18.         }  
    19.         function getClientCoordinates(e) {  
    20.             x2 = e.clientX;  
    21.             y2 = e.clientY;  
    22.             $(".sp2").text("X2:" + x2 + ",Y2:" + y2);  
    23.         }  
    24.         function getPageCoordinates(e) {  
    25.             x3 = e.pageX;  
    26.             y3 = e.pageY;  
    27.             $(".sp3").text("X3:" + x3 + ",Y3:" + y3);  
    28.         }  
    29.     });  
    30. </script>  
    31. </head>  
    32. <body>  
    33. <p>test</p>  
    34. <p>test</p>  
    35. <p>test</p>  
    36. <p>test</p>  
    37. <p>test</p>  
    38. <p>test</p>  
    39. <p>test</p>  
    40. <p>test</p>  
    41. <p>test</p>  
    42. <p>test</p>  
    43. <p>test</p>  
    44.     <p>  
    45.         鼠标当前屏幕的坐标为:<span class="sp1"></span>  
    46.     </p>  
    47.     <p>  
    48.         鼠标当前窗口客户区坐标为:<span class="sp2"></span>  
    49.     </p>  
    50.     <p>  
    51.         鼠标当前页面区域中的坐标为:<span class="sp3"></span>  
    52.     </p>  
    53.     <p>test</p>  
    54.     <p>test</p>  
    55.     <p>test</p>  
    56.     <p>test</p>  
    57.     <p>test</p>  
    58.     <p>test</p>  
    59.     <p>test</p>  
    60.     <p>test</p>  
    61.     <p>test</p>  
    62.     <p>test</p>  
    63.     <p>test</p>  
    64. </body>  
    65. </html>  

猜你喜欢

转载自690878204.iteye.com/blog/2301675