Numpad没有从CharCode中给出数字

Numpad not giving numbers in fromCharCode

本文关键字:数字 CharCode Numpad      更新时间:2023-09-26

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

问题是String.fromCharCode中的numpads值与实际字符不对应。。。

还有一点要注意,我的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"中,而不是按键上的keyCode

String.fromCharCodeevent.keyCode不同。

String.fromCharCode期望Unicode代码作为参数,然后返回与其相关联的字符。

按键事件中的event.keyCode实现有点令人困惑,它们返回的是被按下按键的代码,而不是打印的字符的代码。然而,在按键事件中使用它将返回预期值和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>