如何从页面加载和鼠标移动中跟踪鼠标位置? [英] How to track mouse position from on page load as well as on mouse move?

查看:107
本文介绍了如何从页面加载和鼠标移动中跟踪鼠标位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下JavaScript跟踪鼠标移动:

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;
}

我的问题是,如果鼠标自页面以来没有移动过加载后,mouseX和mouseY值都等于0.如何在加载页面时以及移动鼠标时获取鼠标值?

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?

推荐答案

浏览器在移动之前不知道鼠标的位置。

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?

出于同样的原因,你无法获得悬停事件如果光标在页面加载时已经悬停,则为item。这些事件需要通过鼠标移动才能触发。

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.

不幸的是这是一个浏览器级别的问题,而不是javascript问题。

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

这篇关于如何从页面加载和鼠标移动中跟踪鼠标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆