如何在setInterval()回调中获取光标位置

How do you get cursor position on setInterval() callback

本文关键字:获取 光标 位置 回调 setInterval      更新时间:2023-09-26

我需要每n秒记录一次鼠标位置,但是jQuery似乎只提供了在有鼠标事件时检索x和y位置值的方法。这可以用setInterval()吗?

EDIT -我想设置一个setInterval()每n秒增加一个值(说' I'),然后在鼠标移动记录当前的I旁边的x和y值。应该有比这更简单的方法

您可以做的是将一个函数绑定到文档上的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);
});

这应该有帮助。

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>

这是一个不使用jQuery的解决方案。虽然我更喜欢jq选项:

http://www.codelifter.com/main/javascript/capturemouseposition1.html

您可以使用event object中可用的.timeStamp属性:

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

当然,这种技术只会在移动鼠标时存储数据。在空闲时间,什么也不会发生。如果您还需要空闲位置,您真的需要使用间隔计时器。

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);
    });

我曾经做过这样的事情,我使用了这种hack的解决方案:

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

这个数组的长度将是您的i。您可以使用split方法获得单个项。

Demo将它们打印到div

两个解决方案,都不使用Jquery:

http://javascript.about.com/library/blmousepos.htm

http://hartshorne.ca/2006/01/23/javascript_cursor_position/