2017-08-29 204 views
4

我正在做一个小jQuery脚本,当我不在我的电脑时可以帮助我做一些事情。像机器人一样。如何模拟长鼠标左键点击

这个机器人必须执行一些左键点击页面上特定的X,Y点。我使用此代码并且完美地工作: document.elementFromPoint(X,Y).click();

但我还需要长时间点击页面的另一个点。 我需要模拟这个: 按住左键(x,y)...等待3秒...释放左键单击。

有没有办法做到这一点?

谢谢。

回答

3

使用纯JavaScript,这可能是不可能的。至少不适合所有情况。

不过,如果您所指定的元件是使mousedownmouseup检测到这种“长鼠标点击”,那么你可能直接触发他们:

document.elementFromPoint(X, Y).mousedown(); 

setTimeout(() => document.elementFromPoint(X, Y).mouseup(), 3000); 

就像我说的,是行不通的在任何情况下,因为你实际上并不是在控制鼠标本身,而应该让你在一些模拟中使用鼠标。

0

把超时听众mousedownmouseup

不是最好代码之间,但你可以做这样的事情:

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