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


当前回答

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

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

其他回答

这是我的解决方案。它导出窗口。currentMouseX和window。你可以在任何地方使用currentMouseY属性。它首先使用悬停元素的位置(如果有的话),然后监听鼠标移动来设置正确的值。

(function () {
    window.currentMouseX = 0;
    window.currentMouseY = 0;

    // Guess the initial mouse position approximately if possible:
    var hoveredElement = document.querySelectorAll(':hover');
    hoveredElement = hoveredElement[hoveredElement.length - 1]; // Get the most specific hovered element

    if (hoveredElement != null) {
        var rect = hoveredElement.getBoundingClientRect();
        // Set the values from hovered element's position
        window.currentMouseX = window.scrollX + rect.x;
        window.currentMouseY = window.scrollY + rect.y;
    }

    // Listen for mouse movements to set the correct values
    window.addEventListener('mousemove', function (e) {
        window.currentMouseX = e.pageX;
        window.currentMouseY = e.pageY;
    }, /*useCapture=*/true);
}())

来源:https://github.com/ocproducts/composr/commit/a851c19f925be20bc16bfe016be42924989f262e#diff-b162dc9c35a97618a96748639ff41251R1202

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

jsfiddle.net/5XzeE/4/

是的,这是可能的。

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

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

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

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

您可以为光标的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);}

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

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

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