处理Alt +在JavaScript中按Enter键

时间:2015-05-26 19:29:34

标签: javascript javascript-events keypress keyboard-events

我试图获取一些纯JavaScript代码来处理文本区域中的 Alt + Enter 按键事件,但是我失败了。有什么问题?

HTML

PATH 20.05.2015,20.05.2015,20.05.2015,20.05.2015,21.05.2015,21.05.2015,21.05.2015,21.05.2015,22.05.2015,22.05.2015,22.05.2015,22.05.2015,22.05.2015,22.05.2015,23.05.2015,24.05.2015,25.05.2015,26.05.2015
RAM 0,,,,1,,,,2,,,,,,,,,
SWAP ,00,,,,11,,,,22,,,,,,,,
/ ,,000,,,,111,,,,222,,,,,,,
/dev ,,,0000,,,,1111,,,,2222,,,,,,
/root ,,,,,,,,,,,,22222,,,,,
/root2 ,,,,,,,,,,,,,222222,333333,444444,555555,666666

的JavaScript

<textarea id="ta" style="width:100%;height:500px">
</textarea>

的jsfiddle

Here

3 个答案:

答案 0 :(得分:5)

Enter是关键代码13,您需要keydownkeyup,而非keypress(适用于可打印字符),您应该使用keyCode而不是charCode。像这样:

ta.onkeydown = function(e) {
    if (e.keyCode == 13 && e.altKey) { ...

答案 1 :(得分:2)

简单修复:使用keyCode代替charCode。 ENTER的keyCode是13。

var ta = document.getElementById('ta');
ta.onkeypress = function(e) {
   if (e.keyCode == 13 && e.altKey){
      alert(
         "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
          + "keyCode: " + e.keyCode + "\n"
          + "Alt key pressed: " + e.altKey + "\n"
      );      
   }
};

答案 2 :(得分:1)

此解决方案基于MDN文档中的this example,似乎是最易于跨浏览器的方式:

var ta = document.getElementById('ta');
ta.onkeydown = function (event) {
    if (event.defaultPrevented) {
       return;
    }
    var handled = false;
    if (event.key !== undefined) {
       if (event.key === 'Enter' && event.altKey) {
          alert('Alt + Enter pressed!');
       }
    } else if (event.keyIdentifier !== undefined) {
       if (event.keyIdentifier === "Enter" && event.altKey) {
          alert('Alt + Enter pressed!');
       }

    } else if (event.keyCode !== undefined) {
       if (event.keyCode === 13 && event.altKey) {
          alert('Alt + Enter pressed!');
       }
    }
    if (handled) {
       event.preventDefault();
    };
};

Updated fiddle