简体   繁体   English

获取键盘数字键中符号的javascript键盘代码

[英]Obtain javascript keycode of symbols in the numeric keys of keyboards

What is the javascript keycode for the / (forward slash) symbol regardless the language and culture of keyboard and OS? /(正斜杠)符号的javascript键盘代码是什么,而不管键盘和操作系统的语言和文化如何? In an English keyboard the forward slash is in a key separate from the numeric keys and it's keycode is 191. However in a Spanish keyboard that character is together with the number 7 in the same key and to type it in I have to do SHIFT + 7, but that combination does not result in keycode 191! 在英语键盘中,正斜杠位于与数字键分开的键中,其键码为191。但是,在西班牙语键盘中,同一键中的字符与数字7一起输入,我必须按SHIFT + 7,但该组合不会产生键码191!

I've tried if (event.shiftKey && event.keyCode == 55) {} where 55 is the keycode of character 7 and it works, but with an English keyboard the if (event.shiftKey && event.keyCode == 55) {} condition allows me to type in the & (ampersand) symbol. 我尝试过if (event.shiftKey && event.keyCode == 55) {}其中55是字符7的if (event.shiftKey && event.keyCode == 55) {} ,它可以正常工作,但是使用英语键盘时, if (event.shiftKey && event.keyCode == 55) {}条件允许我输入&(&)符号。

I have a textbox in my web page for which I only want to allow users to type in digits and forward slash regardless the language of the keyboards or OSs they are using and regardless the have to press just one key to enter the forward slash or they have to do a combination of SHIFT + a numeric key or another type of combination. 我的网页上有一个文本框,我只希望用户输入数字和正斜杠,而不管他们使用的键盘或操作系统的语言是什么,而不必只按一个键就可以输入正斜杠。必须执行SHIFT +数字键的组合或其他类型的组合。 How can I do this? 我怎样才能做到这一点?

As an alternative to preventing the keypress: 作为防止按键的替代方法:

<textarea oninput="validate(this,/([^\/\d])/g)" ></textarea>
<script>
function validate(inp,reg)
{
    //([^\/\d]) translates to:
    //"remove everything that is not a / or a number"
    var s = inp.selectionStart;
    inp.value = inp.value.replace(reg,"");
    inp.selectionStart = s;inp.selectionEnd = s;//reset caret position
}
</script>

You can achieve this by listening to keypress instead of keydown, this will give you an event object that contains the actual key pressed and the corresponding ASCII code. 您可以通过监听按键而不是按下按键来实现此目的,这将为您提供一个事件对象,其中包含实际按下的键和相应的ASCII代码。

// Vanilla JavaScript
document.body.addEventListener('keypress', function(event) { 
  console.log(event);     
});

// jQuery
$('body').on('keypress', function (event) {
  console.log(event);
};

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM