【问题标题】:listen for when mouse has stopped moving监听鼠标何时停止移动
【发布时间】:2021-07-01 22:51:16
【问题描述】:

使用反应: 我有这个初始 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)
      }
    }

【问题讨论】:

标签: reactjs settimeout addeventlistener cleartimeout removeeventlistener


【解决方案1】:

您可以在每次鼠标移动时清除超时,因此当用户停止移动时,将调用重置样式函数:


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);
  };
}, []);

【讨论】:

    猜你喜欢
    • 2015-07-06
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-17
    相关资源
    最近更新 更多