JavaScript KeyCode 与 CharCode

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4285627/
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-08-23 11:44:15  来源:igfitidea点击:

JavaScript KeyCode vs CharCode

javascriptkeycode

提问by Remotec

The problem:

问题:

  • Limit allowed characters in a HTML input to a-z A-Z only.
  • For business requirements this needs to be done on KeyPress so that the character simply isnt allowed to even appear in the input.
  • Tab, enter, arrows, backspace, shift are all allowed. The user must be able to freely move in and out of the textbox, delete characters etc etc.
  • 将 HTML 输入中允许的字符限制为仅 az AZ。
  • 对于业务需求,这需要在 KeyPress 上完成,以便字符根本不允许出现在输入中。
  • Tab、Enter、箭头、退格、shift 都是允许的。用户必须能够自由进出文本框,删除字符等。

This is the starting point of my code...

这是我的代码的起点...

var keyCode = (e.keyCode ? e.keyCode : e.which);

However every value that I get in keyCodedoesnt correspond to anyof the character charts I have seen on the web. For example the character "h" gives me a return code of 104.

然而,我在keyCode 中获得的每个值都与我在网上看到的任何字符图表都不对应。例如,字符“h”给了我 104 的返回码。

Is KeyCode different to CharCode? Which code contains the control characters? Do I need to convert?

KeyCode 与 CharCode 不同吗?哪个代码包含控制字符?我需要转换吗?

How can I restrict the input to a-z A-Z and allow the keys I need in JavaScript?

如何限制对 az AZ 的输入并允许我在 JavaScript 中使用所需的键?

回答by Tim Down

The answers to all your questions can be found on the following page.

您可以在下一页找到所有问题的答案。

...but in summary:

...但总而言之:

  • The only event from which you can reliably obtain character information (as opposed to key code information) is the keypressevent.
  • In the keypressevent, all browsers except IE <= 8 store the character code in the event's whichproperty. Most but not all of these browsers also store the character code in the charCodeproperty.
  • In the keypressevent, IE <= 8 stores the character code in the keyCodeproperty.
  • 您可以从中可靠地获取字符信息(与键码信息相反)的唯一事件是keypress事件。
  • keypress事件中,除 IE <= 8 之外的所有浏览器都将字符代码存储在事件的which属性中。大多数但不是所有这些浏览器也将字符代码存储在charCode属性中。
  • keypress事件中,IE <= 8 将字符代码存储在keyCode属性中。

This means to get the character code corresponding to the keypress, the following will work everywhere, assuming a keypress event object is stored in a variable called e:

这意味着要获取与按键对应的字符代码,假设按键事件对象存储在名为 的变量中,以下内容将适用于任何地方e

var charCode = (typeof e.which == "number") ? e.which : e.keyCode

This will generally return you a character code where one exists and 0 otherwise. There are a few cases where you'll get a non-zero value when you shouldn't:

这通常会返回一个字符代码,其中一个存在,否则返回 0。在某些情况下,您会在不应该得到非零值的情况下:

  • In Opera < 10.50 for keys Insert, Delete, Homeand End
  • In recent versions of Konqueror for non-character keys.
  • 在Opera <10,50键InsertDeleteHomeEnd
  • 在用于非字符键的 Konqueror 的最新版本中。

The workaround for the first problem is a little involved and requires using the keydownevent as well.

第一个问题的解决方法有点复杂,还需要使用keydown事件。

回答by nicopolyptic

Good grief. KeyboardEvent.[key, char, keyCode, charCode, which] are all deprecated or currently have outstanding bugs according to Mozilla's API docs - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent. Even JQuery passes the buck on this one and lets the user figure it out https://api.jquery.com/keydown/.

好伤心。根据 Mozilla 的 API 文档 - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent,KeyboardEvent.[key, char, keyCode, charCode, which] 均已弃用或目前存在未解决的错误。甚至 JQuery 也在这个问题上推卸责任,让用户弄清楚https://api.jquery.com/keydown/

回答by Han Seoul-Oh

Actually, 104 is the ASCII code for lowercase 'h'. To get the ASCII code of the typed character onkeypress, you can just use e.which || e.keyCode, and you don't need to worry about held down keys because for typed text, keypress is auto-repeated in all browsers (according to the excellent http://unixpapa.com/js/key.html).

实际上,104 是小写“h”的 ASCII 码。要在e.which || e.keyCode按键上获取键入字符的 ASCII 代码,您可以使用,并且您无需担心按下按键,因为对于键入的文本,按键在所有浏览器中都会自动重复(根据优秀的http:// unixpapa.com/js/key.html)。

So all you really need is:

所以你真正需要的是:

<input id="textbox">

<script type="text/javascript">
document.getElementById('textbox').onkeypress = function(e){
  var c = e.which || e.keyCode;
  if((c > 31 && c < 65) || (c > 90 && c < 97) || (c > 122 && c !== 127))
    return false;
};
</script>

Try it: http://jsfiddle.net/wcDCJ/1/

试试看:http: //jsfiddle.net/wcDCJ/1/

(The ASCII codes are from http://en.wikipedia.org/wiki/Ascii)

(ASCII 代码来自http://en.wikipedia.org/wiki/Ascii

回答by James Long

onKeyPress has different codes for upper and lower case letters. You'd probably find that turning on the cap-lock and then typing your letter would give you the code you expect

onKeyPress 对大写和小写字母有不同的代码。你可能会发现打开大写锁定然后输入你的信会给你你期望的代码

onKeyUp and onKeyDown have the same character codes for upper and lower-case letters. It'd recommend using onKeyUp because it's the closest to onKeyPress

onKeyUp 和 onKeyDown 具有相同的大写和小写字母字符代码。建议使用 onKeyUp 因为它最接近 onKeyPress

回答by Mac

Here is example markup:

这是示例标记:

<form id="formID">
    <input type="text" id="filteredInput">
    <input type="text" id="anotherInput">
</form>

The following logic can be used to trap for keyboard input (in this case, via a jQuery document ready wrapper).

以下逻辑可用于捕获键盘输入(在本例中,通过 jQuery 文档就绪包装器)。

It may read a little goofy, but basically, I check for everything I want to allow for (in your case, the letters A through Z case insensitive) and do nothing. In other words, the default action is allowed, but any input other than alpha is prevented.

它可能读起来有点傻,但基本上,我检查了我想要允许的所有内容(在您的情况下,字母 A 到 Z 不区分大小写)并且什么都不做。换句话说,默认操作是允许的,但除了 alpha 之外的任何输入都被阻止。

Standard keyboard navigation, such as arrow keys, Home, End, Tab, Backspace, Delete and so forth are checked for and allowed.

检查并允许使用标准键盘导航,例如箭头键、Home、End、Tab、Backspace、Delete 等。

NOTE: This code was originally written to satisfy user input permitting only alphanumeric values (A - Z, a - z, 0 - 9), and I left those lines intact as comments.

注意:此代码最初是为了满足仅允许字母数字值(A - Z、a - z、0 - 9)的用户输入而编写的,并且我将这些行作为注释完好无损。

        <script>
            jQuery( document ).ready( function() {

                // keydown is used to filter input
                jQuery( "#formID input" ).keydown( function( e ) {
                    var _key = e.which
                        , _keyCode = e.keyCode
                        , _shifted = e.shiftKey
                        , _altKey = e.altKey
                        , _controlKey = e.ctrlKey
                    ;
                    //console.log( _key + ' ' + _keyCode + ' ' + _shifted + ' ' + _altKey + ' ' + _controlKey );

                    if( this.id === jQuery( '#filteredInput' ).prop( 'id' ) ) {
                        if(
                            // BACK,         TAB
                            ( _key === 8 || _key === 9 )    // normal keyboard nav
                        ){}

                        else if(
                            // END,           HOME,          LEFT,          UP,            RIGHT,         DOWN
                            ( _key === 35 || _key === 36 || _key === 37 || _key === 38 || _key === 39 || _key === 40 )  // normal keyboard nav
                        ){}

                        else if(
                            // DELETE
                            ( _key === 46 ) // normal keyboard nav
                        ){}

                        else if(
                            ( _key >= 65 && _key <= 90 )    // a- z

                            //( _key >= 48 && _key <=  57 && _shifted !== true ) ||   // 0 - 9 (unshifted)
                            //( _key >= 65 && _key <=  90 ) ||                        // a- z
                            //( _key >= 96 && _key <= 105 )                           // number pad 0- 9
                        ){}

                        else {
                            e.preventDefault();
                        }
                    }

                });
            });
        </script>

回答by kennebec

/* You won't get a keyCode on keypress for non-printing keys, why not capture them on keydown instead? */

/* 你不会在 keypress 上获得非打印键的 keyCode,为什么不在 keydown 上捕获它们呢?*/

function passkeycode(e){
    e= e || window.event;
    var xtrakeys={
        k8: 'Backspace', k9: 'Tab', k13: 'Enter', k16: 'Shift', k20: 'Caps Lock',
        k35: 'End', k36: 'Home', k37: 'Ar Left', k38: 'Ar Up', k39: 'Ar Right',
        k40: 'Ar Down', k45: 'Insert', k46: 'Delete'
    },
    kc= e.keyCode;
    if((kc> 64 && kc<91) || xtrakeys['k'+kc]) return true;
    else return false;
}

inputelement.onkeydown=passkeycode;

kc> 64 && kc<91 // a-zA-Z

kc> 64 && kc<91 // a-zA-Z

xtrakeys['k'+integer]) defines special keycodes allowed

xtrakeys['k'+integer]) 定义允许的特殊键码

回答by jqeryandjavascriptarenotthesam

I think you're taking the wrong approach entirely. How about something like:

我认为你完全采取了错误的方法。怎么样:

<input id="test">

<script type="text/javascript">
var aToZ = function(el){
    if(this.value.match(/[^a-zA-Z]/)){
        this.value = this.value.replace(/[^a-zA-Z]+/, '')
    }
}
document.getElementById("test").onkeyup = aToZ
</script>

Also, don't forget to repeat the check server-side too.

另外,不要忘记重复检查服务器端。

回答by David M?rtensson

I think keyCode returns the ASCII key value, Ascii-104 is h.

我认为 keyCode 返回 ASCII 键值,Ascii-104 是 h。

http://www.asciitable.com/

http://www.asciitable.com/

Charcode is as noted in another answer an alternative used in some browsers.

Charcode 如另一个答案中所述,是某些浏览器中使用的替代方法。

Here is a article with a crssbrowser example: http://santrajan.blogspot.com/2007/03/cross-browser-keyboard-handler.html

这是一篇带有 crssbrowser 示例的文章:http://santrajan.blogspot.com/2007/03/cross-browser-keyboard-handler.html