zoukankan      html  css  js  c++  java
  • 获取鼠标在盒子内的坐标

    案例分析:

    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>
  • 相关阅读:
    第四章、Vue组件
    第三章、Vue实例
    第二章、Vue指令
    Python练习实例012
    Python练习实例011
    Python练习实例010
    Python练习实例009
    Python练习实例008
    Python练习实例007
    Python练习实例006
  • 原文地址:https://www.cnblogs.com/cy1227/p/12973548.html
Copyright © 2011-2022 走看看