所以我想到了一个页面烦人的用户:当用户没有移动鼠标时,它应该在鼠标位置显示一个图层,并且在鼠标移动时也会隐藏它,但会有延迟。
我有延迟部分使用jQuery的延迟()。但我不确定实现OnMouseNotMoving的最佳方法是什么。
jQuery中是否有'计时器',即当鼠标不移动时会启动,并且会在足够的时间过后触发事件?
THX。
答案 0 :(得分:3)
在mousemove上,您可以添加使用setTimeout()和clearTimeout()方法。像这样:
var timeout = null;
$(document).bind('mousemove', function(e) {
// use e.pageX and e.pageY to position your message
// clear and set timeout
if(timeout) {
hideMessage();
clearTimeout(timeout);
}
timeout = setTimeout(function(x, y){
return showMessage(x, y);
}(e.pageX, e.pageY), 3000);
function showMessage(x, y) {
// your code to show message
}
function hideMessage() {
}
});
答案 1 :(得分:1)
您必须自己创建此活动。 Javascript本身有计时器。 setInterval()
是您正在寻找的方法。它将以指定的间隔执行一个函数。
如果鼠标坐标在指定的时间间隔内没有移动,您可以进行基本检查,然后再进行操作。
答案 2 :(得分:0)
据我所知,但为什么不创建一个获取鼠标位置的间隔并检查它是否已更改:
var x, y, time, mouseTimeout = 2000;
function checkPosition(e) {
var t = new Date();
if (e.clientX !== x || e.clientY !== y) {
//mouse changed
time = t;
x = e.clientX;
y = e.clientY;
}
if ((t - time) > mouseTimeout) {
//annoy users
}
}
<body onmousemove="checkPosition();">
</body>