首页 > 解决方案 > 查找容器内的实时鼠标坐标

问题描述

因此,我涉足 JavaScript 坐标并创建了一个容器,其中鼠标的 x 和 y 坐标将显示在容器内。

该代码几乎可以正常工作,只是它仅在我进入容器时才显示坐标并且除非我重新进入容器才会更改。这是下面的代码: -

<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>king crimson</title>
</head>
 
<body>
  <style>
    body{
      display: flex;
      align-items: center;
      align-content: center;
    }
    .container{
      width: 500px;
      height: 400px;
      background-color: crimson;
      margin: auto;
      color: white;
      padding-top: 2rem;
      text-align: center;
    }
  </style>
<div class="container"></div>

<!-- START JAVASCRIPT -->

  <script>
    const box = document.querySelector('.container');
    
    box.addEventListener('mouseover', e =>{
      let x = event.clientX;
      let y = event.clientY;
      const coords = `
      Coordinate of x is ${x} and coordinate of y is ${y}
      `

      box.innerHTML = coords;
    });
  </script>

<!-- END JAVASCRIPT-->
</body>

</html>

标签: javascripthtmlcssmouseevent

解决方案


  const box = document.querySelector('.container');
    
    box.addEventListener('mousemove', e =>{
      let x = event.clientX;
      let y = event.clientY;
      const coords = `
      Coordinate of x is ${x} and coordinate of y is ${y}
      `;

      box.innerHTML = coords;
    });
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>king crimson</title>
</head>
 
<body>
  <style>
    body{
      display: flex;
      align-items: center;
      align-content: center;
    }
    .container{
      width: 500px;
      height: 400px;
      background-color: crimson;
      margin: auto;
      color: white;
      padding-top: 2rem;
      text-align: center;
    }
  </style>
<div class="container"></div>




<!-- END JAVASCRIPT-->
</body>

</html>


推荐阅读