如何在没有事件的情况下(不移动鼠标),获取鼠标位置?

375

在页面加载后,是否可以使用JavaScript获取鼠标位置,而无需任何鼠标移动事件(不需要移动鼠标)?


71
mousemove事件本身没有问题。只是在某些情况下,用户不移动鼠标。感谢您的回答。 - Norbert Tamas
2
Norbert Tamas,@SuperNova的答案(直到今年才添加)表明mouseenter适用于此,因为它在页面加载时触发(如果鼠标在视口中)。2010年不是这样工作的吗,还是没有人想尝试它? - Peter Hansen
2
在某些情况下(例如用户脚本),您不希望通过添加许多“mousemove”事件来减慢浏览器的速度。 - Tomáš Zato
在Firefox中可以通过鼠标悬停实现,但在IE和Chrome中不行。 - Elad
为了提高此解决方案的性能:
  • 创建一个高度为1像素,宽度为100%的元素,并添加:hover伪类
  • 从文档顶部一像素一像素地扫描以查找Y位置
  • 获取Y坐标后,在X轴上进行扫描(这次元素只能是1px x 1px)
- Pawel
显示剩余3条评论
15个回答

1

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

jsfiddle.net/5XzeE/4/


看起来除非用户有显式的鼠标移动,否则这些技巧已经不再有效了。 :( - trusktr

1

如果你想获取当前光标位置(用于获取最后一个键入字符等情况),则需要注意光标位置而不是鼠标位置。下面的代码片段可以很好地帮助你,它将给出与文本内容相关的光标索引。

window.getSelection().getRangeAt(0).startOffset

1

参考@SuperNova的答案,这里提供一种使用ES6类的方法,可以在回调函数中保持this的上下文正确:

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


0

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

您可以在父页面上使用JHarding的代码,以便最新位置始终可在全局变量中使用:

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

这不会帮助那些通过其他方式导航到此页面的用户。


-1

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接