How to find out mouse coordinates (setTimeout issue)?
Here's the code that explains it all:
$('#elem123').mouseenter(function () {
s开发者_高级运维etTimeout(function () {
//what are mouse coords?
}, 650);
});
Mouse coordinates after the 650 ms have elapsed, and relative to the element, I am guessing? (Adapted from http://docs.jquery.com/Tutorials:Mouse_Position)
See a working demo
var mouseX = 0, mouseY = 0;
$(document).mousemove(function(event) {
mouseX = event.pageX;
mouseY = event.pageY;
});
$('#elem123').mouseenter(function () {
var t = this;
setTimeout(function () {
var localMouseX = mouseX - t.offsetLeft;
var localMouseY = mouseY - t.offsetTop;
}, 650);
});
Why use mousemove
and offsetLeft
? The reason is that the mouse position is only available to us when such an event happens (and only relative to the entire page). jQuery does not provide a more direct way to obtain it.
Read Mouse Position
Try
$('#elem123').mouseover(function (e) {
var xPos = e.pageX;
var yPos = e.pageY;
setTimeout(function () {
alert(xPos);
alert(yPos);
}, 650);
});
See a working demo
精彩评论