最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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

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

Share Improve this question edited Jan 30, 2021 at 23:04 Brian Tompsett - 汤莱恩 5,89372 gold badges61 silver badges133 bronze badges asked Dec 9, 2010 at 17:36 BabikerBabiker 18.8k28 gold badges82 silver badges127 bronze badges 3
  • 8 Key ≠ character. – Gumbo Commented Dec 9, 2010 at 17:37
  • +1, May i ask for an elaboration? – Babiker Commented Dec 9, 2010 at 17:39
  • Quite simple: not every key corresponds to a character. Some examples of non-character keys are the arrow keys. Or Control, Alt and Shift. Or the function keys. – BoltClock Commented Dec 9, 2010 at 18:05
Add a comment  | 

5 Answers 5

Reset to default 10

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

Additionally you can check for e.shiftKey.

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.

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.

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

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.

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>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论