每隔指定时间间隔获取鼠标位置的 JavaScript 示例


要捕获指定时间间隔后的鼠标位置,代码如下。以下代码捕获鼠标位置 -

示例

 在线演示

<!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>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
   font-size: 18px;
   font-weight: 500;
   color: blueviolet;
}
</style>
</head>
<body>
<h1>Capture mouse position after every given interval</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click on the above button to start capturing mouse position every 3 seconds</h3>
<script>
let resultEle = document.querySelector(".result");
let check;
let xCoord, yCoord;
document.body.addEventListener("mousemove", function (event) {
   xCoord = event.clientX;
   yCoord = event.clientY;
});
function displayCoordinate(element) {
   resultEle.innerHTML =
   "X coordinate = " + xCoord + "<br> Y coordinate = " + yCoord;
}
document.querySelector(".Btn").addEventListener("click", () => {
   setInterval(displayCoordinate, 3000);
});
</script>
</body>
</html>

输出

点击“单击此处”按钮,鼠标位置将每 3 秒捕获一次 -

更新于: 06-May-2020

168 次浏览

开启您的职业生涯

完成课程即可获得认证

开始学习
广告