Javascript - 模拟空格键按键 [英] Javascript - Emulate a space bar keypress

查看:367
本文介绍了Javascript - 模拟空格键按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处搜索,阅读MDN上的文档,但我似乎无法解决这个问题。

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

我想模仿客户端按空格使用Javascript吧。

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

我试过:

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 被记录到控制台。

由于某种原因,事件被触发但关键始终是 0

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

有人可以帮我解决吗?

推荐答案

你可以这样做

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

演示: https://jsfiddle.net/5se13tmg/

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

这篇关于Javascript - 模拟空格键按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆