如何获取删除键的event.keyCode?

时间:2014-01-21 03:35:44

标签: events keypress keycode

$('body').keypress(function(event){

     if(event.keyCode == 46){console.log('Delete Key Pressed')}; //does not work

     if(event.keyCode == 32){console.log('SPACE BAR')}; //works
})

Why doesn't the delete key show up in THIS FIDDLE ?

2 个答案:

答案 0 :(得分:19)

使用keyup或keydown事件代替keypress:keypress用于PRINTABLE字符,而keydown将捕获非打印键按下,包括delete,backspace和return。 http://jsfiddle.net/5cNTn/9/

$('body').keydown(function(event){
    var letter = String.fromCharCode(event.which); 
    if(event.keyCode == 32){console.log('SPACE BAR');}
    if(event.keyCode == 46){console.log('Delete Key Pressed');}
    console.log(event); 
    console.log(event.keyCode); 
 });

答案 1 :(得分:4)

使用keydown和现代JS!

document.addEventListener("keydown", function(event) {
    if (event.key === "Delete") {
        // Do something
    }
});