Is there a way to trigger mousemove and get event.pageX, event.pageY?

后端 未结 6 1739
温柔的废话
温柔的废话 2020-12-05 23:23

So, like the question specifies, is there a way to trigger a mousemove event in jQuery which also sends the mouse coordinates to the event Object?

So far my code can

6条回答
  •  忘掉有多难
    2020-12-06 00:19

    I don't believe it possible to get the mouse coordinates on demand via JavaScript / jQuery; however if you bind the position to a global var you can then access them at anytime throughout the document like this:

    $(document).ready(function(){
       $().mousemove(function(e){
          window.xPos = e.pageX;
          window.yPos = e.pageY;
       }); 
    });
    

    for a less CPU intensive option, you can add a timeout, although you trade performance for a slight delay in knowing where the mouse is:

    function getMousePosition(timeoutMilliSeconds) {
        $(document).one("mousemove", function (event) {
            window.xPos = event.pageX;
            window.yPos = event.pageY;
            setTimeout("getMousePosition(" + timeoutMilliSeconds + ")", timeoutMilliSeconds);
        });
    }
    getMousePosition(100);
    

    You should now be able to access the window.xPos and window.yPos from anywhere in the document using either solution without needing to trigger a faux event.

提交回复
热议问题