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


当前回答

我想我可能有一个合理的解决方案,不用计算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);
}  

其他回答

var x = 0;
var y = 0;

document.addEventListener('mousemove', onMouseMove, false)

function onMouseMove(e){
    x = e.clientX;
    y = e.clientY;
}

function getMouseX() {
    return x;
}

function getMouseY() {
    return y;
}

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

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

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

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

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

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

重复@超新星的回答,这里有一个使用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));

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

jsfiddle.net/5XzeE/4/