绑定多个键到按键事件 [英] Bind Multiple Keys to Keypress Event

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

问题描述

  $(document).keydown(function( e){
switch(e.keyCode){

案例39:
e.preventDefault();
alert(Arrow Key);
break;

case 37:
e.preventDefault();
alert(Arrow Key);
}
});

但我想知道的是,如果我可以而不是绑定一个键绑定两个键的组合。我可以这样做:

  $(document).keydown(function(e){
switch .keyCode){
case 39&& && 37:
e.preventDefault();
alert(Arrow Key);
break;
}
});


解决方案

如果你想一次检查多个键,你应该只能使用一个常规键和一个或多个修饰键(alt / shift / ctrl),因为您无法确定用户键盘上可以同时按下两个常规键(实际上,它们总是可以按下,但PC可能不会你可以使用e.altKey,e.ctrlKey,e.shiftKey字段来检查匹配的修饰符键是否为



示例:

  $(document).keydown function(e){
if(e.which == 98& e.ctrlKey){
// ctrl + b pressed
}
});


I am currently using this Javascript kepypress code to fire events upon keypress:

$(document).keydown(function(e) {
    switch(e.keyCode) {

    case 39:
        e.preventDefault();
        alert("Arrow Key");
        break;

    case 37:
        e.preventDefault();
        alert("Arrow Key");
    }
});

but what i am wondering is if i can instead of binding one key bind a combination of two keys. Could I possibly do something like:

$(document).keydown(function(e) {
    switch(e.keyCode) { 
        case 39 && 37:
            e.preventDefault();
            alert("Arrow Key");
        break;
    }
});

解决方案

If you want to check multiple keys at once you should only use one regular key and one or more modifier keys (alt/shift/ctrl) as you cannot be sure that two regular keys can actually be pressed at once on the user's keyboard (actually, they can always be pressed but the PC might not understand it due to the way keyboards are wired).

You can use the e.altKey, e.ctrlKey, e.shiftKey fields to check if the matching modifier key was pressed.

Example:

$(document).keydown(function(e) {
    if(e.which == 98 && e.ctrlKey) {
        // ctrl+b pressed
    }
});

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

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