我正在编写一个jQuery脚本,在我离开电脑时帮助我完成一些工作。类似于机器人。
这个机器人必须在页面的特定X,Y点上执行一些左键单击操作。
我使用以下代码并且运行得很完美:document.elementFromPoint(X, Y).click();
但我还需要在页面的另一点上进行长按操作。我需要模拟这样的操作:按下左键(x,y) ... 等待3秒钟...释放左键。
有办法做到这样吗?
谢谢。
我正在编写一个jQuery脚本,在我离开电脑时帮助我完成一些工作。类似于机器人。
这个机器人必须在页面的特定X,Y点上执行一些左键单击操作。
我使用以下代码并且运行得很完美:document.elementFromPoint(X, Y).click();
但我还需要在页面的另一点上进行长按操作。我需要模拟这样的操作:按下左键(x,y) ... 等待3秒钟...释放左键。
有办法做到这样吗?
谢谢。
document.elementFromPoint(X, Y).mousedown();
setTimeout(() => document.elementFromPoint(X, Y).mouseup(), 3000);
正如我所说,这种方法并不适用于所有情况,因为您实际上并没有控制鼠标本身,但是可以让您在某些情况下模拟它。
mousedown
和 mouseup
之间加入一个超时监听器。function listenForLongClick (domElement, timeout = 3000) {
let mouseDownStarted = false;
let timeoutCheck = null;
domElement.addEventListener('mousedown', () => {
mouseDownStarted = true;
timeoutCheck = setTimeout(() => mouseDownStarted = false, timeout);
}, false);
domElement.addEventListener('mouseup', () => {
clearTimeout(timeoutCheck);
if (mouseDownStarted) { console.log('within the 3 seconds'); }
mouseDownStarted = false;
}, false);
}