我需要每n秒记录鼠标位置,但jQuery似乎只提供了在鼠标事件发生时检索x和y位置值的方法。可以用setInterval()吗?
完成编辑 - 我想设置一个setInterval()来每n秒增加一个值(比如'i'),然后在mousemove上记录当前i和x和y值。确实应该有一个比这更简单的方法
答案 0 :(得分:2)
您可以做的是将一个函数绑定到文档上的mousemove事件,并在函数内部设置一个带有鼠标位置的全局变量。然后每个间隔都可以读取鼠标位置。
示例:
$(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 :(得分:1)
这应该有所帮助。
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>
答案 2 :(得分:0)
这是一个不使用jQuery的解决方案。虽然我更喜欢jq选项:
http://www.codelifter.com/main/javascript/capturemouseposition1.html
答案 3 :(得分:0)
我必须做一次这样的事情,我使用了这种hacky解决方案:
document.onmousemove=function(){
x = e.pageX;
y = e.pageY;
}
setInterval(function(){
array.push(x+','+y);
},'1000');
这个数组的长度将是你的i。您可以使用split方法获取单个字词。
答案 4 :(得分:0)
您可以使用.timeStamp
中提供的event object
媒体资源:
var stored = 0;
$( document ).mousemove(function( event ) {
if( event.timeStamp - stored >= 2000 ) {
console.log('stored!');
stored = event.timeStamp;
}
});
当然,该技术只会在移动鼠标时存储数据。在空闲时间,没有任何反应。如果你还需要空闲位置,你真的需要使用间隔计时器。
答案 5 :(得分: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);
});
答案 6 :(得分:0)