javascript 鼠标停止移动时执行Jquery
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17252532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
execute Jquery when the mouse stops moving
提问by Ryan Saxe
I have a quick script that has a trail follow the cursor:
我有一个跟踪光标的快速脚本:
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);
});
});
Now I would like to remove the animate
part and have something like the following when the mouse is not moving:
现在,animate
当鼠标不移动时,我想移除该部件并具有以下内容:
$('.fall').each(function(){
$(this).fadeOut('slow');
$(this).remove()
});
I just can't figure out how to execute this when the mouse is not moving for more than like a second. Any ideas?
当鼠标不移动超过一秒钟时,我无法弄清楚如何执行此操作。有任何想法吗?
Thanks, and here is a jsfiddle
采纳答案by Varun
回答by adeneo
You add a timeout that fires after one second of inactivity, and clear the timeout if the mouse moves within 1 second etc :
您添加一个在不活动一秒后触发的超时,并在鼠标在 1 秒内移动时清除超时等:
var timer;
$(document).on('mousemove', function(e){
clearTimeout(timer);
timer = setTimeout(function() {
$('.fall').fadeOut('slow', function() {
$(this).remove();
});
}, 1000);
});
EDIT:
编辑:
Here's how I'd do it
这是我的方法