JavaScript – 获取鼠标坐标


要使用 JavaScript 获取鼠标坐标,代码如下 -

示例

 实时演示

<!DOCTYPE html>
<html>
<head>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 25px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>Coordinates of mouse</h1>
<p class="sample"></p>
<h3>Hover the mouse over the screen to get its x and y axis position</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   document.body.addEventListener("mousemove", (event) => {
      sampleEle.innerHTML = "X axis: " + event.x + " Y axis: " + event.y;
   });
</script>
</body>
</html>

输出

以上代码将产生以下输出


更新日期:07-5-2020

399 个浏览量

开启你的 职业生涯

通过完成课程获取认证

开始
广告
© . All rights reserved.