So I was thinking of annoying users of a page a little bit: when user is not moving a mouse, it should display a layer at mouse position, and also hide开发者_如何学运维 it when mouse moves, with a delay.
I have delay part figured out using jQuery's delay(). But I'm not sure what would be the best way to implement OnMouseNotMoving.
Is there a 'timer' in jQuery, i.e. something that would start when mouse doesn't move, and that would fire an event after enough time passes?
Thx.
On mousemove you can add use the setTimeout() and clearTimeout() methods. Something like this:
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() {
}
});
You have to create this event yourself. Javascript itself has timers. setInterval()
is the method you are looking for. It will execute a function at a specified interval.
You basicly check the mouse coordinates if they have not moved for a specified interval, and then do your thing.
Not so far as i know, but why not create an interval that gets the mouse position and check if it's changed:
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>
精彩评论