Get mouse coordinates in the case of the box

Objective function

Here Insert Picture Description

Code

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    div {
      width: 200px;
      height: 200px;
      margin: 100px auto;
      background-color: tomato;
    }
  </style>
</head>

<body>
  <div></div>
  
  <script>
    var div = document.querySelector('div');

    div.addEventListener('mousemove', function (e) {
      var x = e.pageX - div.offsetLeft;
      var y = e.pageY - div.offsetTop;
      div.innerHTML = '鼠标的横坐标:' + x + '<br>鼠标的纵坐标:' + y;
    });
  </script>
</body>

</html>
Published 135 original articles · won praise 0 · Views 3091

Guess you like

Origin blog.csdn.net/qq_35764106/article/details/105213018