在 JavaScript 中处理 Alt + Enter 按键

Handling Alt + Enter key press in JavaScript

我正在尝试获取一些纯 JavaScript 代码来处理文本中的 Alt + Enter 按键事件区域,但失败得很惨。怎么了?

Html

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

JavaScript

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

JSFiddle

Here

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

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

简单修复:使用 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"
      );      
   }
};

这个基于 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