有没有办法触发mousemove并获取event.pageX,event.pageY? [英] Is there a way to trigger mousemove and get event.pageX, event.pageY?
问题描述
所以,就像问题指定的那样,有没有办法在jQuery中触发mousemove事件,它还将鼠标坐标发送到事件对象?
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?
到目前为止我的代码可以使用.trigger(事件)函数触发mousemove,但event.pageX和event.pageY是未定义的。
So far my code can trigger the mousemove using the .trigger(event) function but the event.pageX and event.pageY are undefined.
推荐答案
我不相信可以通过JavaScript / jQuery按需获取鼠标坐标;但是,如果您将该位置绑定到全局变量,则可以随时在整个文档中访问它们,如下所示:
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;
});
});
对于CPU密集度较低的选项,您可以添加超时,尽管您会稍微延迟交换性能知道鼠标在哪里:
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);
您现在应该能够使用文档中的任何位置访问window.xPos和window.yPos任何解决方案都不需要触发虚假事件。
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.
这篇关于有没有办法触发mousemove并获取event.pageX,event.pageY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!