按键同时按下 [英] Keys pressed at the same time

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

问题描述

我可以在Javascript中知道同时按下的键数吗?

Can I know the number of keys pressed at the same time in Javascript?

如果是这样,我怎么能得到一个的数组? keyCode

If so, how can I have an array of their keyCode?

推荐答案

您可以收听keydown和keyup事件。

You can listen for keydown and keyup events.

var keys = { length: 0 };

document.onkeydown = function(e){
    if(!keys[e.keyCode])   {
        keys[e.keyCode] = true;
        keys.length++;
    }
}

document.onkeyup = function(e){
    if(keys[e.keyCode])   {
        keys[e.keyCode] = false;
        keys.length--;
    }
}

然后所有 true 是当前按下的那些。

Then all the keys that are true are the ones that are pressed currently.

小提示演示感谢@Esailija: http://jsfiddle.net/maniator/Gc54D/

Fiddle demo thanks to @Esailija: http://jsfiddle.net/maniator/Gc54D/

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

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