温馨提示×

onmousemove事件如何获取坐标

小樊
81
2024-07-02 04:37:36
栏目: 编程语言

可以使用event对象中的clientX和clientY属性来获取鼠标在页面中的坐标位置。示例代码如下:

<!DOCTYPE html>
<html>
<head>
<title>获取鼠标坐标</title>
<script>
function showCoords(event) {
  var x = event.clientX;
  var y = event.clientY;
  document.getElementById("coords").innerHTML = "鼠标坐标:(" + x + ", " + y + ")";
}
</script>
</head>
<body onmousemove="showCoords(event)">
<p id="coords"></p>
</body>
</html>

在上面的示例中,onmousemove事件会触发showCoords函数,并将event对象传递给该函数。showCoords函数中通过event.clientX和event.clientY获取鼠标的坐标位置,并将坐标显示在页面上。

0