zoukankan      html  css  js  c++  java
  • 获取鼠标的位置

    一、获取绝对、相对值

     1 <!DOCTYPE HTML>
     2 <html lang="en-US">
     3 
     4     <head>
     5         <meta charset="UTF-8" />
     6         <title>位置</title>
     7         <script language="javascript" type="text/javascript">
     8             function m() {
     9                 document.getElementById("area").innerHTML = event.clientX + " , " + event.clientY;
    10             }
    11 
    12             function c() {
    13                 //objTop objLeft 获取的是 例如获得鼠标在一个div中点击的绝对位置,这个便是这个div的 值
    14                 var objTop = getOffsetTop(document.getElementById("d")); //对象x位置
    15                 var objLeft = getOffsetLeft(document.getElementById("d")); //对象y位置
    16                 //mouseX,mouseY获取的是鼠标的位子相对于整个文档的,包括了文档很长所产生的滚动条的值
    17                 //clientX,clientY获取的是鼠标相对于屏幕的,不包括滚动条的值
    18                 var mouseX = event.clientX + document.body.scrollLeft; //鼠标x位置
    19                 var mouseY = event.clientY + document.body.scrollTop; //鼠标y位置
    20                 //计算点击的相对位置
    21                 var objX = mouseX - objLeft;
    22                 var objY = mouseY - objTop;
    23                 clickObjPosition = objX + "," + objY;
    24                 alert(clickObjPosition);
    25             }
    26             //计算
    27             function getOffsetTop(obj) {
    28                 var tmp = obj.offsetTop;
    29                 var val = obj.offsetParent;
    30                 while(val != null) {
    31                     tmp += val.offsetTop;
    32                     val = val.offsetParent;
    33                 }
    34                 return tmp;
    35             }
    36 
    37             function getOffsetLeft(obj) {
    38                 var tmp = obj.offsetLeft;
    39                 var val = obj.offsetParent;
    40                 while(val != null) {
    41                     tmp += val.offsetLeft;
    42                     val = val.offsetParent;
    43                 }
    44                 return tmp;
    45             }
    46         </script>
    47     </head>
    48 
    49     <body style="margin:0px;" onmousemove="m();">
    50         <div style="padding:90px;border:1px solid #ccc;font-size:36px;400px;height:400px;"> </div>
    51         <div id="area"></div>
    52         <div style="400px;height:400px;border:1px solid red;">
    53             <div id="d" style="300px;height:300px;border:2px solid pink;padding:10px;cursor:hand;" onclick="c()"></div>
    54         </div>
    55     </body>
    56 
    57 </html>
  • 相关阅读:
    黑松白鹿
    跨越
    第三年
    Lua windows环境搭建
    Iron man
    水果沙拉
    六周岁
    sqlserver数据库附加报错5120
    [BeiJing2006]狼抓兔子 平面图最小割
    BZOJ2118: 墨墨的等式 思维建图
  • 原文地址:https://www.cnblogs.com/haonanZhang/p/6297302.html
Copyright © 2011-2022 走看看