Numpad 不在 fromCharCode 中给出数字

Numpad not giving numbers in fromCharCode

我只想在我的输入字段中允许某些按键。

问题是 String.fromCharCode 中的小键盘值与实际字符不对应...

另请注意,我的 chrome 将逗号 (String.fromCharCode(188)) 翻译成“¼” - 尽管它应该是“,” ?

我是这样做的:

Javascript 指令:

angular.module('LTS').directive('allowed', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs, modelCtrl) {
            var allowedLowerCaseLetters = attrs.allowed.toLowerCase();
            element.on('keydown', function (event) {
                var pressedChar = String.fromCharCode(event.keyCode).toLowerCase();
                if (event.keyCode === 188) {
                    pressedChar = ",";
                }
                if (allowedLowerCaseLetters.indexOf(pressedChar) > -1 || event.keyCode === 8 || event.keyCode === 37 || event.keyCode === 39) {
//                    console.log(pressedChar+" should be added to model.");
                } else {
                    //TODO maybe add a notification ?
                    event.preventDefault();
                }
            });
        }
    };
});

HTML:

<input id="invoiceAmount" class="form-control importInput" type="text" ng-model="import.invoiceAmount"  allowed="1234567890,">

小心 Firefox 在 "event.charCode" 中有它的代码,而不是 keypress

中的 keyCode

String.fromCharCode and event.keyCode不一样。

String.fromCharCode 期望 Unicode 代码作为参数,然后 return 与它们关联的字符。

event.keyCode 在 keydown 事件中 实现有点混乱,它们 return 被按下的键的代码而不是打印的字符的代码。但是,在按键事件中使用它会 return 预期值和在 String.fromCharCode.

中使用的正确值

 function f(e){
  document.querySelector('div').innerHTML += e.type + ' - ' + e.keyCode + ' - ' + String.fromCharCode(e.keyCode) + '<br/>';
  }

document.querySelector('input').addEventListener('keydown', f);
document.querySelector('input').addEventListener('keypress', f);
<input />
<div></div>