我正在尝试在网页中设置一个脚本,该脚本执行以下操作:如果鼠标在一定时间(例如五秒)内处于非事件状态,则执行一个操作(例如隐藏一个元素);然后,如果鼠标移动,则执行一个操作(例如,取消隐藏该元素)。
我想要的是某种方法来对用户鼠标不活动(不一定是键盘不活动)执行操作。
感谢您的帮助。
最佳答案
如果您使用的是 jQuery:
(function() {
var timeout;
var isHidden = false;
$(document).mousemove(function() {
if (timeout) {
window.clearTimeout(timeout);
}
timeout = window.setTimeout(function() {
if (!isHidden) {
//hide the element here
isHidden = true;
}
}, 5000);
if (isHidden) {
//show the element here
isHidden = false;
}
});
})();
非 jQuery 版本:
(function() {
var timeout;
var isHidden = false;
function hideOnIdle() {
if (timeout) {
window.clearTimeout(timeout);
}
timeout = window.setTimeout(function() {
if (!isHidden) {
//hide the element here
isHidden = true;
}
}, 5000);
if (isHidden) {
//show the element here
isHidden = false;
}
}
if (document.addEventListener) {
document.addEventListener("mousemove", hideOnIdle);
} else {
document.attachEvent("onmousemove", hideOnIdle);
}
})();
关于javascript - 在 JavaScript 中对空闲状态执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4482155/