每隔指定時間間隔獲取滑鼠位置的 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 次瀏覽

開啟您的職業生涯

完成課程即可獲得認證

開始學習
廣告
© . All rights reserved.