开发者

Simulate an event to get mouse coordinates?

开发者 https://www.devze.com 2023-01-23 12:53 出处:网络
I need to get mouse coordinate at the moment th开发者_JS百科e setTimeout function calls the provided function.You need to use a mousemove event handler to keep track of the mouse\'s coordinates in a s

I need to get mouse coordinate at the moment th开发者_JS百科e setTimeout function calls the provided function.


You need to use a mousemove event handler to keep track of the mouse's coordinates in a scope that's accessible by your setTimeout() callback. Then, your setTimeout() callback can just check the values you've stored from the mousemove handler.

At a high level, it would look something like this (pseudocode):

var mouseX, mouseY;
document.addListener('onMouseMove', function (event)
{
    mouseX = event.getMouseX(); // in reasonable browsers, this would be
    mouseY = event.getMouseY(); // event.pageX and event.pageY
});

// then, when you want to retrieve it later...
setTimeout(function ()
{
    console.log(mouseX, mouseY);
}, 1000);

Personally, I'd recommend using a third-party library such as jQuery, YUI, Dojo, etc. to smooth out all the cross-browser differences in event handling, if you're not doing so already.


Doing it with setTimeout would be problematic, because you'd have no event object to work with. You could, however, handle "mousemove" on the <body> and keep track that way. The event object passed to the handler (or, in the case of IE, set up globally) will have the x, y coordinates of the mouse at the time the event occurred.


function getValues()
{
    var s = 'X=' + window.event.clientX +  ' Y=' + window.event.clientY ;
    return s;

}  

setTimeout ( getValues, 10000);
0

精彩评论

暂无评论...
验证码 换一张
取 消