2011-11-02 84 views
3

我需要每隔n秒记录鼠标位置,但jQuery似乎只提供了在出现鼠标事件时检索x和y位置值的方法。这可以通过setInterval()完成吗?我想设置一个setInterval()每n秒增加一个值(比如'i'),然后在mousemove上记录下当前的i和x和y值。真的应该有一个比这更简单的方法,虽然如何在setInterval()回调中获取光标位置

回答

2

你可以做的是一个功能绑定到文档上的鼠标移动事件,在函数内部用鼠标位置的全局变量。那么每隔一段时间你就可以读取鼠标的位置。

例如:

$(document).ready(function() { 
    var mousePosition = {'x': 0, 'y': 0}; 
    $(document).bind('mousemove', function(e) { 
     mousePosition = {'x': e.pageX, 'y': e.pageY}; 
    }); 

    setInterval(function() { 
     // do something with mousePosition 
    }, 1000); 
}); 
1

这应该有所帮助。

http://jsbin.com/owifu3/

http://docs.jquery.com/Tutorials:Mouse_Position

还不如将代码粘贴...

<html> 
<head> 
<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript"> 
jQuery(document).ready(function(){ 
    $(document).mousemove(function(e){ 
     $('#status').html(e.pageX +', '+ e.pageY); 
    }); 
}) 
</script> 
<body> 
<h2 id="status"> 
0, 0 
</h2> 
</body> 
</html> 
+0

这是一个良好的网页,但每个例子依赖于鼠标事件(无论是鼠标移动()或点击())。我想知道是否可以在计时器事件而不是鼠标事件上完成 –

0

我不得不做这样的事情,有一次,我用这种哈克解决方案:

document.onmousemove=function(){ 
x = e.pageX; 
y = e.pageY; 
} 
setInterval(function(){ 
array.push(x+','+y); 
},'1000'); 

这个数组的长度将是你我。您可以使用split方法获取单个术语。

Demo that just prints them to a div

0

你可以使.timeStamp财产是在event object可用的用法:

var stored = 0; 

$(document).mousemove(function(event) { 
    if(event.timeStamp - stored >= 2000) { 
     console.log('stored!'); 
     stored = event.timeStamp; 
    } 
}); 

当然,该技术将只存储数据,同时移动鼠标。闲暇时,没有任何反应。如果你还需要空闲位置,你真的需要一个间隔计时器。

0
jQuery(document).ready(function(){ 
    var myx, myy; 
    $(document).mousemove(function(e){ 
     myx = e.pageX; 
     myy = e.pageY); 
    }); 
    window.setInterval(function() { 
     $('#status').html('mouse position is '+myx+','+myy); 
     }, 1000); 
    });