确定事件之外的鼠标位置(使用jQuery)?

pbz*_*pbz 38 mouse jquery position event-handling

我需要使用(最好)jQuery来保持绝对鼠标位置/坐标(X和Y),就像在本教程中一样,但在任何JavaScript事件之外.谢谢.

Che*_*try 47

不可能.但是,您可以在教程中使用相同的方法将位置存储在全局变量中,并在事件外部读取它.

像这样:

jQuery(document).ready(function(){
   $().mousemove(function(e){
      window.mouseXPos = e.pageX;
      window.mouseYPos = e.pageY;
   }); 
})
Run Code Online (Sandbox Code Playgroud)

您现在可以使用window.mouseXPoswindow.mouseYPos从任何地方.

  • @pbz这是一个JavaScript限制. (4认同)
  • 我刚刚设置了一个jQuery.one('mousemove',function(){}); 以此目的.使用setTimeout延迟它,在下次移动时捕获鼠标位置,瞧. (4认同)

eye*_*ess 29

这开始是对Chetan Sastry的答案的评论,但我意识到它也可能值得作为答案发布:

mousemove即使您只是轮询光标位置,我也要小心拥有一个文档级别的,始终运行的事件.这是一个很大的处理,可以阻止任何浏览器,特别是像IE这样的慢速浏览器.

像这样的问题几乎肯定会引发设计决策的问题:如果你不需要处理鼠标事件来轮询光标位置,你真的需要光标位置吗?有没有更好的方法来解决您试图解决的问题?

编辑:即使在Safari 4中,这是(低估)非常快,单一mousemove事件使得与该教程页面的每次互动对我来说都明显不稳定.考虑一下这将如何影响用户对您网站或应用程序的看法.


小智 10

此函数将通过仅以一定间隔获取鼠标位置来减少对UI性能的影响:

function getMousePosition(timeoutMilliSeconds) {
    // "one" attaches the handler to the event and removes it after it has executed once 
    $(document).one("mousemove", function (event) {
        window.mouseXPos = event.pageX;
        window.mouseYPos = event.pageY;
        // set a timeout so the handler will be attached again after a little while
        setTimeout(function() { getMousePosition(timeoutMilliSeconds) }, timeoutMilliseconds);
    });
}

// start storing the mouse position every 100 milliseconds
getMousePosition(100);
Run Code Online (Sandbox Code Playgroud)

正如在其他的答案:"你现在可以使用window.mouseXPoswindow.mouseYPos从任何地方."

由于在间隔期间不会检测到鼠标移动,因此会失去一点准确性.

  • 你应该避免使用类似eval的结构.它们效率较低,并且存在潜在的安全风险.`setTimeout(function(){getMousePosition(timeoutMilliSeconds)},timeoutMilliseconds);` (6认同)