繁体   English   中英

页面加载后如何跟踪不活动的鼠标?

[英]How to track an inactive mouse once a page loads?

现在,我有一个 function 设置,如果鼠标处于非活动状态 10 秒,则仅用于移动设备 但是我的 console.log 不会出现,除非在它被不活动触发之前有一些活动。 这是我的代码:

    if (width <= 480) {
       const inactiveUserMessage = () => {
             console.log("mouse has been inactive for 10 seconds");
       };
       document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000));
    }
    

***在另一个文件中,存在去抖动 function:

export function debounce(func, timeout) {
    let timer;
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}

在 inactiveUserMessage 触发之前需要有某种活动。 但是我该怎么做去抖动 function 立即运行而不需要之前的某种运动? 请帮忙!!!

请让我知道这是否有意义,或者您是否需要更多信息。

我试图创建一个带有去抖动 function 的 mousemove 事件侦听器,但它不起作用,除非事先页面上有某种移动。

我试图创建一个带有去抖动 function 的 mousemove 事件侦听器,但它不起作用,除非事先页面上有某种移动。

使用窗口的“加载”事件启动定时器并将定时器传递给去抖动 function。像这样;

let timer;
const inactiveUserMessage = () => {
     console.log("mouse has been inactive for 10 seconds");
};

window.addEventListener("load", () => {
     timer = setTimeout(inactiveUserMessage, 10000);
});

...

if (width <= 480) {
    document.addEventListener("mousemove", debounce(inactiveUserMessage, 10000), timer);
}
...
export function debounce(func, timeout, timer) {
    return (...args) => {
        if (timer) {
            clearTimeout(timer);
        }
        timer = setTimeout(() => {
            func.apply(this, args);
        }, timeout);
    };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM