Javascript - 模拟空格键按键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34017695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript - Emulate a space bar keypress
提问by Oliver
I've searched everywhere, read the docs on MDN, but I can't seem to solve this problem.
我到处搜索,阅读 MDN 上的文档,但我似乎无法解决这个问题。
I want to emulate the client pressing the space bar using Javascript.
我想模拟客户端使用 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.
0
记录到控制台。
For some reason, the event is triggered but the key is always 0
由于某种原因,事件被触发,但关键总是 0
Can someone help me fix it?
有人可以帮我解决吗?
回答by R Lam
You may do on this way
你可以这样做
var e = new KeyboardEvent('keydown',{'keyCode':32,'which':32});
var e = new KeyboardEvent('keydown',{'keyCode':32,'which':32});
Demo: https://jsfiddle.net/5se13tmg/
演示:https: //jsfiddle.net/5se13tmg/
Reference: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
参考:https: //developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
回答by J. Gobet
Create your event variable like that :
像这样创建您的事件变量:
var e = new Event('keydown');