JavaScript KeyCode 与 CharCode

发布于 2024-10-04 04:29:48 字数 453 浏览 4 评论 0原文

问题:

  • 将 HTML 输入中允许的字符限制为 az AZ。
  • 对于业务需求,这需要在 KeyPress 上完成,以便该字符根本不允许出现在输入中。
  • Tab、Enter、箭头、退格键、Shift 都可以。用户必须能够自由移入和移出文本框、删除字符等。

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

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

但是我在 keyCode 中获得的每个值并不对应于 < em>任何我在网上看到的人物图表。例如,字符“h”给我的返回码为 104。KeyCode

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

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

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.

This is the starting point of my code...

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

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

自我难过 2024-10-11 04:29:48

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

...但总而言之:

  • 您可以可靠地获取字符信息(而不是按键代码信息)的唯一事件是 keypress 事件。
  • keypress 事件中,除 IE <= 8 之外的所有浏览器都将字符代码存储在事件的 which 属性中。大多数(但不是全部)这些浏览器还将字符代码存储在 charCode 属性中。
  • keypress 事件中,IE <= 8 将字符代码存储在 keyCode 属性中。

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

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

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

  • 在 10.50 对于键 InsertDeleteHomeEnd
  • 在最新版本的 Konqueror 中,对于非字符键。

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

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 keypress event.
  • In the keypress event, all browsers except IE <= 8 store the character code in the event's which property. Most but not all of these browsers also store the character code in the charCode property.
  • In the keypress event, IE <= 8 stores the character code in the keyCode property.

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:

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:

  • In Opera < 10.50 for keys Insert, Delete, Home and End
  • In recent versions of Konqueror for non-character keys.

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

暮光沉寂 2024-10-11 04:29:48

好悲伤。根据 Mozilla 的 API 文档,KeyboardEvent.[key、c​​har、keyCode、charCode,which] 均已弃用或当前存在突出的错误 - https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent。甚至 JQuery 也在这个问题上推卸了责任,让用户自己解决https://api.jquery.com/keydown/

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/.

意中人 2024-10-11 04:29:48

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

所以你真正需要的是:

<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>

尝试一下:http://jsfiddle.net/wcDCJ/1/

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

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).

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/

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

寒冷纷飞旳雪 2024-10-11 04:29:48

onKeyPress 对于大小写字母有不同的代码。您可能会发现,打开大写锁定,然后输入字母会得到您期望的代码,

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

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

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

世界如花海般美丽 2024-10-11 04:29:48

/*
对于非打印按键,您不会在按键时获得 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

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

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

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

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

一腔孤↑勇 2024-10-11 04:29:48

下面是示例标记:

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

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

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

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

注意:此代码最初是为了满足仅允许字母数字值(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>

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).

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.

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

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.

        <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>
花落人断肠 2024-10-11 04:29:48

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

http://www.asciitable.com/

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

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

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

http://www.asciitable.com/

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

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

溺ぐ爱和你が 2024-10-11 04:29:48

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

<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>

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文