Javascript String.charCodeAt(index)和keyCodes [英] Javascript String.charCodeAt(index) and keyCodes

查看:89
本文介绍了Javascript String.charCodeAt(index)和keyCodes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Javascript KeyCode vs CharCode = Utter Confusion

什么是 String.charCodeAt(index)的返回值与JavaScript密钥代码之间的差异?有没有办法在两者之间进行翻译?

What is the difference between the return value of String.charCodeAt(index) and JavaScript key codes? And is there a way to translate between the two?

例如:

console.log('.'.charCodeAt(0));  // prints 46 on Mac/Chrome

但'。'的keyCode为190。

But the keyCode for '.' is 190.

推荐答案

string.charCodeAt(index)旨在返回指定位置的字符串字符的ascii值。

string.charCodeAt(index) is designed to return you the ascii value for the character of a string at a specified position.

keyCode是按下的键盘键值的浏览器实现。不幸的是,它并没有在所有浏览器中标准化。

keyCode is the browser implementation of what the value for the keyboard key that was pressed. unfortunately, it's not standardized across all browsers either.

编辑:

String.fromCharCode(unicodeValue);

这会将unicode值(如keyCode)转换为ascii值。请注意,并非所有keyCode值都将转换为适当的ascii值(因为没有),如{delete,up,down,left,right,home,insert,page up,page down}等按键操作

This will convert a unicode value such as keyCode into an ascii value. Just be mindful that not all keyCode values are going to convert to an appropriate ascii value (since there isn't one) such key presses like { delete, up, down, left, right, home, insert, page up, page down }

示例:如果执行 alert(String.fromCharCode(46)),按Delete键会返回keyCode为46; 你会看到它输出一段时间,因为46是一段时间的ascii值。

Example: pressing the Delete key returns a keyCode of 46, if you do alert(String.fromCharCode(46)); you will see it output a period since the 46 is the ascii value for a period.

这篇关于Javascript String.charCodeAt(index)和keyCodes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆