监听鼠标何时停止移动
listen for when mouse has stopped moving
使用反应:
我有这个初始的 eventListener,它在我的视频元素中侦听 mousemove,然后我想侦听的是一个代码,它检测鼠标何时停止移动以启动这样的计时器:
// initial listener
useEffect(() => {
vidRef.current.addEventListener('mousemove', displayOpa)
return () => {
vidRef.current.removeEventListener('mousemove', displayOpa)
}
}, [])
函数 displayOpa:
const displayOpa = () => {
controlsBackgroundRef.current.style.opacity = 1;
vidControlsRef.current.style.opacity = 1;
// basically here I want to start this timer when the mouse has stopped moving only how would I say that?
// like
if ("mouse has stopped moving then run code below") {
const initialSwitch = setTimeout(() => {
controlsBackgroundRef.current.style.opacity = 0;
vidControlsRef.current.style.opacity = 0;
}, 5000)
}
}
您可以在每次鼠标移动时清除超时,因此当用户停止移动时将调用重置样式函数:
useEffect(() => {
let timeout = 0;
const displayOpa = () => {
controlsBackgroundRef.current.style.opacity = 1;
vidControlsRef.current.style.opacity = 1;
clearTimeout(timeout);
timeout = setTimeout(() => {
controlsBackgroundRef.current.style.opacity = 0;
vidControlsRef.current.style.opacity = 0;
}, 5000);
};
vidRef.current.addEventListener('mousemove', displayOpa);
return () => {
vidRef.current.removeEventListener('mousemove', displayOpa);
};
}, []);
使用反应: 我有这个初始的 eventListener,它在我的视频元素中侦听 mousemove,然后我想侦听的是一个代码,它检测鼠标何时停止移动以启动这样的计时器:
// initial listener
useEffect(() => {
vidRef.current.addEventListener('mousemove', displayOpa)
return () => {
vidRef.current.removeEventListener('mousemove', displayOpa)
}
}, [])
函数 displayOpa:
const displayOpa = () => {
controlsBackgroundRef.current.style.opacity = 1;
vidControlsRef.current.style.opacity = 1;
// basically here I want to start this timer when the mouse has stopped moving only how would I say that?
// like
if ("mouse has stopped moving then run code below") {
const initialSwitch = setTimeout(() => {
controlsBackgroundRef.current.style.opacity = 0;
vidControlsRef.current.style.opacity = 0;
}, 5000)
}
}
您可以在每次鼠标移动时清除超时,因此当用户停止移动时将调用重置样式函数:
useEffect(() => {
let timeout = 0;
const displayOpa = () => {
controlsBackgroundRef.current.style.opacity = 1;
vidControlsRef.current.style.opacity = 1;
clearTimeout(timeout);
timeout = setTimeout(() => {
controlsBackgroundRef.current.style.opacity = 0;
vidControlsRef.current.style.opacity = 0;
}, 5000);
};
vidRef.current.addEventListener('mousemove', displayOpa);
return () => {
vidRef.current.removeEventListener('mousemove', displayOpa);
};
}, []);