How to track mouse position from on page load as well as on mouse move?

↘锁芯ラ 提交于 2019-12-30 08:11:26

问题


I am tracking mouse movements using the following JavaScript:

var mouseX = 0;
var mouseY = 0;

document.onmousemove = function (e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
}

My problem is that if the mouse hasn't been moved since the page had been loaded, the mouseX and mouseY values both equal 0. How can I get the mouse values when the page is loaded as well as when the mouse is moved?


回答1:


The browser doesn't know where the mouse is until it moves.

It's more complicated than just "get me the cursor position". What if there is no mouse (tablet) or what if the mouse is not over the browser window?

For the same reason, you can't get hover events on an item if the cursor is already hovering when the page loads. It takes a mouse movement for those events to fire.

Go to some site, hover over a link that has a hover effect (like underline), refresh the page (without moving your cursor) and you'll see that even though your cursor is hovering over the link, it doesn't get the hover treatment until you move the cursor.

Unfortunately this is a browser-level issue, not a javascript issue.




回答2:


You can define mouseover event for the document in order to catch the first mouse interaction on page load.



来源:https://stackoverflow.com/questions/8013062/how-to-track-mouse-position-from-on-page-load-as-well-as-on-mouse-move

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!