Blogger Information
Blog 24
fans 1
comment 0
visits 21771
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
实时获取鼠标在div中的坐标--2019年3月29日
王先生的博客
Original
707 people have browsed it

通过听课和练习  使用入口函数, 获取元素 获取xy的坐标 最终显示在页面中  鼠标使用的是e.client  而元素使用的是  offsetLeft/Top  思路清晰了 不蓝 哈


实例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style type="text/css">
    #box{
      width: 500px;
      height: 500px;
      margin: 0 auto;
      background: pink;
    }
  </style>
</head>
<body>
  <p>当前坐标是:<b id="show">(0,0)</b></p>
  <p>div内部坐标是:<b id="show1">(0,0)</b></p>
  <div id="box"></div>
</body>
<script type="text/javascript">
  window.onload=function(){
    var show=document.getElementById('show');
    var box=document.getElementById('box');
    var show1=document.getElementById('show1');
    window.onmousemove=function(event){
      var e=event||window.event;
      var x=e.clientX;
      var y=e.clientY;   
      show.innerHTML="("+x+","+y+")";
    }
    box.onmousemove=function(event){
      var e=event||window.event;
      var x=e.clientX;
      var y=e.clientY;
      var b_x=box.offsetLeft;
      var b_y=box.offsetTop;
      var show_x=x-b_x;
      var show_y=y-b_y;
      show1.innerHTML="("+show_x+","+show_y+")";
    }
  }
</script>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


本小节需要记忆的是

1:入口函数  页面加载完成后就执行  window.onload

2:鼠标移动事件: onmousemove

3:兼容  var e=event||window.event;

4:鼠标获取坐标    e.clientX/Y

5:元素获取坐标  this.offsetTop  前提是在本函数中 如果不是 就要使用获取到的元素变量


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post