Выполнить JQuery, когда мышь перестает перемещаться
У меня есть быстрый script, который следит за курсором:
jQuery(document).ready(function(){
$(document).mousemove(function(e){
$('.fall').each(function(){
if ($(this).css("opacity") == 0){
$(this).remove();
};
});
t = (e.pageY - 10).toString() + 'px';
l = (e.pageX - 10).toString() + 'px';
$('.fall').css("margin_left",l);
$('.fall').css("margin_top",t);
var doit = '<div class="fall" style="position:fixed;margin-left:' + l + ';margin-top:' + t + ';">+</div>'
$('body').prepend(doit);
$('#status2').html(e.pageX +', '+ e.pageY);
$('.fall').animate({
marginTop: '+=50px',
opacity: 0
},1000);
});
});
Теперь я хотел бы удалить часть animate
и сделать что-то вроде следующего, когда мышь не движется:
$('.fall').each(function(){
$(this).fadeOut('slow');
$(this).remove()
});
Я просто не могу понять, как это выполнить, когда мышь не движется больше, чем секунда. Любые идеи?
Спасибо, и вот jsfiddle
Ответы
Ответ 1
это то, что вам нужно? jsFiddle
lastTimeMouseMoved = new Date().getTime();
var t = setTimeout(function() {
var currentTime = new Date().getTime();
if (currentTime - lastTimeMouseMoved > 1000) {
$('.fall').fadeOut('slow');
// $('.fall').remove();
}
}, 1000)
Ответ 2
Вы добавляете тайм-аут, который срабатывает после одной секунды бездействия, и очищайте таймаут, если мышь перемещается в течение 1 секунды и т.д.:
var timer;
$(document).on('mousemove', function(e){
clearTimeout(timer);
timer = setTimeout(function() {
$('.fall').fadeOut('slow', function() {
$(this).remove();
});
}, 1000);
});
FIDDLE
EDIT:
Вот как бы я это сделал
FIDDLE