最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Emulate a space bar keypress - Stack Overflow

programmeradmin3浏览0评论

I've searched everywhere, read the docs on MDN, but I can't seem to solve this problem.

I want to emulate the client pressing the space bar using JavaScript.

I've tried:

var e = new KeyboardEvent('keydown');
e.which = e.keyCode = 32; // 32 is the keycode for the space bar
document.dispatchEvent(e);

However this hasn't worked for whatever reason; if the following event handler is put before the above code:

document.addEventListener('keydown', function(ev){
  console.log(ev.which);
});

0 is logged to the console.

For some reason, the event is triggered but the key is always 0

Can someone help me fix it?

I've searched everywhere, read the docs on MDN, but I can't seem to solve this problem.

I want to emulate the client pressing the space bar using JavaScript.

I've tried:

var e = new KeyboardEvent('keydown');
e.which = e.keyCode = 32; // 32 is the keycode for the space bar
document.dispatchEvent(e);

However this hasn't worked for whatever reason; if the following event handler is put before the above code:

document.addEventListener('keydown', function(ev){
  console.log(ev.which);
});

0 is logged to the console.

For some reason, the event is triggered but the key is always 0

Can someone help me fix it?

Share Improve this question edited Apr 25, 2023 at 15:30 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Dec 1, 2015 at 10:09 OliverOliver 1,6441 gold badge19 silver badges32 bronze badges 1
  • 1 @Satpal The API used in the answer there is deprecated now. I have tried using the answer but it failed. – Oliver Commented Dec 1, 2015 at 10:14
Add a comment  | 

2 Answers 2

Reset to default 8

You may do on this way

var e = new KeyboardEvent('keydown',{'keyCode':32,'which':32});

Demo: https://jsfiddle.net/5se13tmg/

Reference: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent

Create your event variable like that :

var e = new Event('keydown');

Demo : https://jsfiddle.net/zw7d7d61/

发布评论

评论列表(0)

  1. 暂无评论