简体   繁体   English

Javascript延迟mousedown事件

[英]Javascript delay a mousedown event

I'm trying to make the following code work: 我正在尝试使以下代码起作用:

document.onmousedown = function(e){
  setTimeout(function(){ e }, 3000);
};

This is just pseudo code, but I want to capture the mousedown event and fire it later. 这只是伪代码,但我想捕获mousedown事件并在以后触发它。 It doesn't matter if it fires the first time or not (ie preventdefault). 它是否第一次触发都没有关系(即preventdefault)。

If this was a click event I know I could just save the clientX, clientY of e and reinitialize the event, but I couldn't find any way to simulate mouse down with JavaScript. 如果这是一个单击事件,我知道我可以保存e的clientX,clientY并重新初始化该事件,但是我找不到用JavaScript模拟鼠标按下的任何方法。

If you want to trigger a mousedown event, just use this api MouseEvent() 如果要触发mousedown事件,只需使用此api MouseEvent()

The MouseEvent() constructor creates a new MouseEvent. MouseEvent()构造函数创建一个新的MouseEvent。

The code is like this: 代码是这样的:

var trigger = false
document.onmousedown = function(e){
    var t = new MouseEvent('mousedown',e)
    console.log(t)
    if(!trigger)
    {
        trigger = true;
        document.dispatchEvent(t)
    }
};

Try this code 试试这个代码

HTML Code: HTML代码:

<p id="myParaid">
Click the text! The mouseDown() function is triggered when the mouse button is pressed down over this paragraph, 
</p>

JS Code: JS代码:

$( "#myParaid" ).mousedown(function() {
  alert( "Handler for .mousedown() called." );
  setTimeout(myFunction, 3000);
});
function myFunction(){
alert('3000 Over');
}

Jsfiddle 的jsfiddle

You can try something like this: 您可以尝试如下操作:

 document.onmousedown = (args) => setTimeout(() => fn.apply(null, [args]), 500) var fn = (args) => { console.log('onmousedown args', args) } 
 Click anywhere and check the console (wait for it) 

If I understand you correctly this will allow you to execute that onmousedown event at a later time with the same params. 如果我理解正确,这将允许您稍后使用相同的参数执行该onmousedown事件。

See it here 在这里看到

Your code has no problem. 您的代码没有问题。 Maybe somewhere else replace the onmousedown listenter. 也许在其他地方替换了onmousedown侦听器。 It's best you use addEventListener 最好使用addEventListener

document.addEventListener("mousedown", function(e) {
setTimeout(function() {
   //your code here
}, 3000)});

or if you are using jQuery, you can use this code 或者,如果您使用的是jQuery,则可以使用此代码

$(document).on("mousedown", function(e) {
    setTimeout(function() {
        //your code here
    }, 3000);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM