我有一个canvas
元素和一个div.coordinates
元素,当鼠标在画布上移动时,该元素跟随鼠标移动。我想做的是,如果鼠标在过去1秒钟内没有在画布上移动,则使.coordinates
消失。
<canvas></canvas>
canvas {
max-width: auto;
outline: 1px solid #283028;
align-self: center;
}
.coordinates {
top: 50px;
position: absolute;
height: 40px;
width: 60px;
background-color: rgba(20, 20, 20, 0.3);
border-radius: 10px;
display: none;
}
let coordinates = document.createElement("div");
coordinates.className = "coordinates";
let time = undefined;
const trackCanvasMouse = (e) => {
if (!time) {
time = Date.now();
}
setTimeout(() => {
if (time == Date.now()) {
coordinates.style.display = "none";
time = undefined;
}
}, 1000);
coordinates.style.top = `${e.clientY}px`;
coordinates.style.left = `${e.clientX}px`;
coordinates.style.display = "inline";
};
const canvas = document.querySelector("canvas");
canvas.addEventListener("mousemove", trackCanvasMouse);
canvas.width = 520;
canvas.height = 520;
document.querySelector("body").appendChild(coordinates);
我尝试使用Time.now()
和setTimeout
来查看事件是否已触发,但无法使其正常工作。
感谢您的时间
答案 0 :(得分:1)
这将显示鼠标移动时的跨度坐标,并在鼠标停止一秒钟后消失。您要做的就是跟踪上一个超时,并在每次mousemove事件触发时将其取消。
let timeout;
const coords = document.getElementById('coords');
document.addEventListener("mousemove", function() {
coords.style.display = "block";
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
coords.style.display = "none";
}, 1000)
});
#coords {
display: none;
}
<span id="coords">Coords</span>