JavaScript get the coordinates of the mouse in the box

Realization ideas:

  1. Click inside the box to get the distance between the mouse and the left and right of the box
  2. First get the coordinates of the mouse on the page e.pageX,e.page
  3. Second, get the distance of the box on the page box.offsetLeft,box.offsetTop
  4. Subtract the distance of the box in the page from the coordinates of the mouse from the page to get the coordinates of the mouse in the box
  5. If you want to move the mouse, get the latest coordinates and use the mouse to movemousemove

effect:

(The mouse disappeared after the screenshot--)
Insert picture description here

Code:

<!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>
        .box {
     
     
            width: 300px;
            height: 300px;
            background-color: pink;
            margin: 200px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        var box = document.querySelector('.box');
        box.addEventListener('mousemove', function(e) {
     
     
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            this.innerHTML = 'x坐标是' + x + ' y坐标是' + y;
        });
    </script>
</body>

</html>

Guess you like

Origin blog.csdn.net/Jack_lzx/article/details/109282572