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

其他回答

是的,这是可能的。

如果你在文档中添加"mouseover"事件,它会立即触发,你可以得到鼠标的位置,当然,如果鼠标指针在文档上。

   document.addEventListener('mouseover', setInitialMousePos, false);

   function setInitialMousePos( event ) {
       console.log( event.clientX, event.clientY);
       document.removeEventListener('mouseover', setInitialMousePos, false);
   }

以前可以通过窗口读取鼠标位置。事件,但现在已弃用。

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

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

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

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

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

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

您不必移动鼠标来获得光标的位置。除了鼠标移动之外,位置也会在其他事件中报告。这里有一个点击事件的例子:

document.body.addEventListener('click',function(e)
{
    console.log("cursor-location: " + e.clientX + ',' + e.clientY);
});