是否有可能获得鼠标位置与JavaScript页面加载后,没有任何鼠标移动事件(不移动鼠标)?


当前回答

真实的答案:不,这是不可能的。

OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 <a> elements (so that the :hover pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover rule for those <a> elements that changes a property (let's say font-family). In your load handler, cycle through each of the 4 million <a> elements, checking currentStyle / getComputedStyle() until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.

N.b.,别这样。

其他回答

编辑2020:这不再工作。看起来是这样,浏览器供应商修补了这个问题。因为大多数浏览器都依赖于chromium,所以它可能位于浏览器的核心。

旧的回答: 您还可以钩子mouseenter(当mousecursor在页面内时,该事件在页面重新加载后触发)。扩展损坏的代码应该做的伎俩:

Var x = null; Var y = null; 文档。addEventListener(' mouemove ', onMouseUpdate, false); 文档。addEventListener('mouseenter', onMouseUpdate, false); 函数onMouseUpdate(e) { x = e.pageX; y = e.pageY; console.log (x, y); } 函数getMouseX() { 返回x; } 函数getMouseY() { 返回y; }

你也可以在mouseleave-event上设置x和y为空。你可以用光标检查用户是否在你的页面上。

我实现了一个水平/垂直搜索,(首先让一个div充满垂直排列的竖线链接,然后让一个div充满水平排列的竖线链接,然后简单地看看哪个有悬停状态),就像Tim Down上面的想法,它工作得相当快。遗憾的是,不工作在Chrome 32上的KDE。

jsfiddle.net/5XzeE/4/

真实的答案:不,这是不可能的。

OK, I have just thought of a way. Overlay your page with a div that covers the whole document. Inside that, create (say) 2,000 x 2,000 <a> elements (so that the :hover pseudo-class will work in IE 6, see), each 1 pixel in size. Create a CSS :hover rule for those <a> elements that changes a property (let's say font-family). In your load handler, cycle through each of the 4 million <a> elements, checking currentStyle / getComputedStyle() until you find the one with the hover font. Extrapolate back from this element to get the co-ordinates within the document.

N.b.,别这样。

您可以为光标的x和y坐标创建变量,每当鼠标移动时更新它们,并在间隔内调用一个函数来对存储的位置执行所需的操作。

当然,这样做的缺点是,至少需要一次初始鼠标移动才能使其工作。只要游标至少更新一次位置,无论它是否再次移动,我们都能够找到它的位置。

var cursor_x = -1;
var cursor_y = -1;
document.onmousemove = function(event)
{
 cursor_x = event.pageX;
 cursor_y = event.pageY;
}
setInterval(check_cursor, 1000);
function check_cursor(){console.log('Cursor at: '+cursor_x+', '+cursor_y);}

上面的代码每秒更新一次,并显示光标所在的位置。

不是鼠标位置,但是,如果你正在寻找当前光标位置(用例,如获取最后键入的字符等),那么,下面的代码片段工作良好。 这将为您提供与文本内容相关的游标索引。

window.getSelection().getRangeAt(0).startOffset