在页面加载后,是否可以使用JavaScript获取鼠标位置,而无需任何鼠标移动事件(不需要移动鼠标)?
在页面加载后,是否可以使用JavaScript获取鼠标位置,而无需任何鼠标移动事件(不需要移动鼠标)?
我实现了一个水平/垂直搜索,(首先创建一个装满垂直线链接的div,水平排列,然后创建一个装满水平线链接的div,垂直排列,然后简单地查看哪个具有悬停状态),就像上面Tim Down的想法一样,它运行得相当快。不幸的是,在KDE上Chrome 32上无法工作。
jsfiddle.net/5XzeE/4/
如果你想获取当前光标位置(用于获取最后一个键入字符等情况),则需要注意光标位置而不是鼠标位置。下面的代码片段可以很好地帮助你,它将给出与文本内容相关的光标索引。
window.getSelection().getRangeAt(0).startOffset
参考@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));
我设想你可能有一个带计时器的父页面,在一定时间或完成任务后,您会将用户转到新页面。现在,您需要光标位置,但因为他们正在等待,不一定触摸鼠标。因此,请使用标准事件跟踪父页面上的鼠标,并通过get或post变量将最后一个值传递给新页面。
您可以在父页面上使用JHarding的代码,以便最新位置始终可在全局变量中使用:
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;
}
这不会帮助那些通过其他方式导航到此页面的用户。
我认为我可能有一个合理的解决方案,而不需要计算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);
}