是否有可能获得鼠标位置与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.,别这样。

其他回答

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

jsfiddle.net/5XzeE/4/

你可以尝试一些类似Tim Down建议的东西——但不是为屏幕上的每个像素设置元素,而是只创建2-4个元素(框),并动态更改它们的位置、宽度和高度,递归地将屏幕上可能的位置除以2-4,从而快速找到鼠标的真实位置。

例如,第一个元素占据屏幕的左右半部分,然后是上下半部分。到目前为止,我们已经知道鼠标位于屏幕的哪四分之一,能够重复—发现这个空间的哪四分之一……

重复@超新星的回答,这里有一个使用ES6类的方法,它在你的回调中保持正确的上下文:

class Mouse { constructor() { this.x = 0; this.y = 0; this.callbacks = { mouseenter: [], mousemove: [], }; } get xPos() { return this.x; } get yPos() { return this.y; } get position() { return `${this.x},${this.y}`; } addListener(type, callback) { document.addEventListener(type, this); // Pass `this` as the second arg to keep the context correct this.callbacks[type].push(callback); } // `handleEvent` is part of the browser's `EventListener` API. // https://developer.mozilla.org/en-US/docs/Web/API/EventListener/handleEvent handleEvent(event) { const isMousemove = event.type === 'mousemove'; const isMouseenter = event.type === 'mouseenter'; if (isMousemove || isMouseenter) { this.x = event.pageX; this.y = event.pageY; } this.callbacks[event.type].forEach((callback) => { callback(); }); } } const mouse = new Mouse(); mouse.addListener('mouseenter', () => console.log('mouseenter', mouse.position)); mouse.addListener('mousemove', () => console.log('mousemove A', mouse.position)); mouse.addListener('mousemove', () => console.log('mousemove B', mouse.position));

最简单的解决方案,但不是100%准确

$(':hover').last().offset()

结果:{上:148,左:62.5} 结果取决于最近的元素大小,当用户切换选项卡时返回undefined

我设想,也许您有一个带有计时器的父页面,在一定时间或任务完成后,您将用户转发到一个新页面。现在你想要光标的位置,因为它们在等待,所以它们不一定会碰到鼠标。因此,使用标准事件跟踪父页面上的鼠标,并通过get或post变量将最后一个值传递给新页面。

你可以在你的父页上使用JHarding的代码,这样最新的位置总是在全局变量中可用:

var cursorX;
var cursorY;
document.onmousemove = function(e){
    cursorX = e.pageX;
    cursorY = e.pageY;
}

这将无法帮助通过父页面以外的方式导航到此页面的用户。