获取鼠标在盒子内的坐标

案例分析:

1.我们在盒子内点击,想要获得鼠标距离盒子左右的距离;

2.首先得到鼠标在页面中的坐标(e.pageX,e.pageY);

3.其次得到盒子在页面中的距离(box.offsetLeft,box.offsetTop);

4.用鼠标距离页面的坐标减去盒子在页面中的距离,得到鼠标在盒子内的坐标;

5.如果想要移动一下鼠标,就要获取最新的坐标,使用鼠标移动事件mousemove。

效果:

代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <style>
 7             .box{
 8                 width: 200px;
 9                 height: 200px;
10                 background-color: pink;
11                 margin: 100px;
12             }
13         </style>
14     </head>
15     <body>
16         <div class="box">
17 
18         </div>
19         <script>
20             var box = document.querySelector('.box');
21             box.addEventListener('mousemove',function(e){
22                 var x = e.pageX - this.offsetLeft;
23                 var y = e.pageY - this.offsetTop;
24                 this.innerHTML = 'x坐标是' + x + ',y坐标是' + y;
25             })
26         </script>
27     </body>
28 </html>

 

posted on 2020-05-27 15:47  SailorM  阅读(715)  评论(0编辑  收藏  举报