簡體   English   中英

Javascript延遲mousedown事件

[英]Javascript delay a mousedown event

我正在嘗試使以下代碼起作用:

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

這只是偽代碼,但我想捕獲mousedown事件並在以后觸發它。 它是否第一次觸發都沒有關系(即preventdefault)。

如果這是一個單擊事件,我知道我可以保存e的clientX,clientY並重新初始化該事件,但是我找不到用JavaScript模擬鼠標按下的任何方法。

如果要觸發mousedown事件,只需使用此api MouseEvent()

MouseEvent()構造函數創建一個新的MouseEvent。

代碼是這樣的:

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

試試這個代碼

HTML代碼:

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

JS代碼:

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

的jsfiddle

您可以嘗試如下操作:

 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) 

如果我理解正確,這將允許您稍后使用相同的參數執行該onmousedown事件。

在這里看到

您的代碼沒有問題。 也許在其他地方替換了onmousedown偵聽器。 最好使用addEventListener

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

或者,如果您使用的是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