简体   繁体   English

JavaScript keydown 事件未通过 setTimeout 触发

[英]JavaScript keydown event is not triggering with setTimeout

I want to automatically trigger a keydown event after specific amount of time has passed.我想在经过特定时间后自动触发keydown事件。 I set up a timout event for this with the code below:我使用以下代码为此设置了一个超时事件:

setTimeout(
    function() {
        document.querySelector("body").dispatchEvent(new KeyboardEvent('keydown', {
            keyCode: 83,
            altKey: true
        }));
    },
    12000
);

However, it doesn't seem to trigger anything.然而,它似乎并没有触发任何东西。 Could anyone please help me in figuring out how can i send a keydown event in such cases?谁能帮我弄清楚在这种情况下如何发送按键事件?

I just tried your code and it triggers alright:我刚试过你的代码,它触发好了:

 document.querySelector("body").addEventListener('keydown', (e) => { console.log('triggered', e) }) setTimeout( function() { document.querySelector("body").dispatchEvent(new KeyboardEvent('keydown', { keyCode: 83, altKey: true })); }, 2000 );

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

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