[英]How can I change the mousemove to setInterval while retaining mouse/element coordinate access?
I'd like to change this to setInterval but I don't know how to do this while keeping access to e.pageX, e.pageY, elem, etc. How can I change this to setInterval (or is there an event in jquery that does the same thing as setInterval but is an event)? 我想将其更改为setInterval,但在保持对e.pageX,e.pageY,elem等的访问权的同时,我不知道该怎么做。如何将其更改为setInterval(或者jquery中是否有事件与setInterval相同,但是是一个事件)?
http://jsfiddle.net/f1Lzqxom/ http://jsfiddle.net/f1Lzqxom/
$(function(){
$(document).on( "mousemove", MouseMove );
var cachedElems = $( '.tracker' );
function MouseMove(e){
var pageX = e.pageX,
pageY = e.pageY;
$.each(cachedElems, function(i,elem){
elem = $(elem);
var elemX = pageX - elem.offset().left,
elemY = pageY - elem.offset().top;
$(elem).text(
'page x: ' + pageX + '\n' +
'page y: ' + pageY + '\n' +
'\n' +
'elem x: ' + elemX + '\n' +
'elem y: ' + elemY + '\n'
);
});
}
});
Change ... 改变...
function MouseMove(e){
...
}
... to ... ... 至 ...
$(document).mousemove(function(e){
window.mouseXPos = e.pageX;
window.mouseYPos = e.pageY;
});
The above code will attach mouse movements to global variables that you can reference inside the setTimeout
. 上面的代码会将鼠标移动附加到可以在
setTimeout
内部引用的全局变量。
setInterval(function() {
var pageX = window.mouseXPos,
pageY = window.mouseYPos;
$.each(cachedElems, function(i,elem){
elem = $(elem);
var elemX = pageX - elem.offset().left,
elemY = pageY - elem.offset().top;
$(elem).text(
'page x: ' + pageX + '\n' +
'page y: ' + pageY + '\n' +
'\n' +
'elem x: ' + elemX + '\n' +
'elem y: ' + elemY + '\n'
);
});
}, 1000);
... with a minor change in variable declaration of pageX
and pageY
to use the new globals. ...对
pageX
和pageY
变量声明进行了较小的更改,以使用新的全局变量。
NOTE : 注意 :
Having provided the answer I did, I would be careful about having a document-level, always-running mousemove
event, even if you're only polling for cursor position. 提供我所做的答案后,即使您只是在查询光标位置,我也要谨慎处理一个文档级,始终运行的
mousemove
事件。 This is a lot of processing and can bog down any browser, particularly slower ones like IE. 这需要大量的处理,并且可能使任何浏览器陷入瘫痪,尤其是速度较慢的浏览器,例如IE。
A problem like this almost certainly raises the question of design decision: if you don't need to handle a mouse event to poll for the cursor position, do you really need the cursor position? 这样的问题几乎可以肯定会引起设计决策的问题:如果您不需要处理鼠标事件来轮询光标位置,那么您真的需要光标位置吗? Is there a better way to solve the problem you're trying to solve?
有没有更好的方法来解决您要解决的问题?
UPDATE : 更新 :
Stopping the set interval can be done this way. 可以通过这种方式停止设置的时间间隔。
var intervalId = setInterval(function() {
...
}, 1000);
/* Later */
clearInterval(intervalId);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.