[英]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');
}
您可以嘗試如下操作:
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.