javascript 使用 e.keyCode || e.哪个;如何确定小写和大写之间的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4401305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 11:17:33  来源:igfitidea点击:

Using e.keyCode || e.which; how to determine the difference between lowercase and uppercase?

javascriptjqueryeventsjavascript-events

提问by Babiker

I am using e.keyCode || e.which;to determine which key was pressed, but I am getting 65 for both aand Awhy is this happening and how can I detect the difference between the two?

我正在使用e.keyCode || e.which;来确定按下了哪个键,但是我得到了 65 个aA为什么会发生这种情况,我如何检测两者之间的差异?

回答by Josiah Ruddell

just use e.whichin jquery. They normalize this value for all browsers.

e.which在jquery中使用。他们为所有浏览器标准化了这个值。

Additionally you can check for e.shiftKey.

此外,您可以检查e.shiftKey.

回答by Bullines

Whether it's 'a' or 'A', 65 is the result of the key pressed on the keyboard and it's always 65 for that key.

无论是 'a' 还是 'A',65 是键盘上按下的键的结果,并且该键始终为 65。

The event will only specify which key is pressed and not its value; those are two separate things. You can test for event.shiftKey along with the key that you're looking for, but I don't believe that will handle the scenario where Caps Lock is enabled.

该事件只会指定按下了哪个键,而不是它的值;这是两件不同的事情。您可以测试 event.shiftKey 以及您正在寻找的键,但我认为这不会处理启用 Caps Lock 的情况。

回答by Pradeep Singh

This script is useful for small and capital letters press

此脚本对于小写和大写字母印刷很有用

<form>
    Char: <input type="text" id="char" size="15" /> Keycode: <input type="text" id="unicode" size="15" />
    </form>

    <script type="text/javascript">

    var charfield=document.getElementById("char")
    charfield.onkeypress=function(e){
    var e=window.event || e
    var keyunicode=e.charCode || e.keyCode
    document.getElementById("unicode").value=keyunicode
    }

    </script>

回答by chaos

This is spectacularly cross-browser-broken in vanilla JavaScript, which is why you should use Josiah Ruddell's solution. See this articlefor more than you want to know.

这在 vanilla JavaScript 中是非常跨浏览器的,这就是为什么您应该使用 Josiah Ruddell 的解决方案。请参阅这篇文章,了解您想知道的更多信息。

回答by tbeseda

keyCode won't indicate which character was input.
To truly find the character last entered by the user you will need to examine the value of the input and find the last character.

keyCode 不会指示输入的是哪个字符。
要真正找到用户最后输入的字符,您需要检查输入的值并找到最后一个字符。