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


当前回答

这是我的解决方案。它导出窗口。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

其他回答

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

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

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

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

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

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

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

我想我可能有一个合理的解决方案,不用计算div和像素..哈哈

简单地使用动画帧或一个时间间隔的函数。你仍然需要一个鼠标事件一次,虽然只是启动,但技术上你可以把它放在任何你喜欢的地方。

从本质上讲,我们一直在跟踪一个虚拟div,没有鼠标移动。

// create a div(#mydiv) 1px by 1px set opacity to 0 & position:absolute;

下面是逻辑。

var x,y;


$('body').mousemove(function( e ) {

    var x = e.clientX - (window.innerWidth / 2);
    var y = e.clientY - (window.innerHeight / 2);
 }


function looping (){

   /* track my div position 60 x 60 seconds!
      with out the mouse after initiation you can still track the dummy div.x & y
      mouse doesn't need to move.*/

   $('#mydiv').x = x;    // css transform x and y to follow 
   $('#mydiv)'.y = y;

   console.log(#mydiv.x etc)

   requestAnimationFrame( looping , frame speed here);
}  

编辑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为空。你可以用光标检查用户是否在你的页面上。