题意:获取键入的字符,跨浏览器兼容
问题背景:
Simple question -- Does anyone know of a reliable cross-browser function to get the character typed from a keydown event? I can write one from the quirksmode grid but would rather not re-invent the wheel for something so simple yet so non-standard.
简单的问题——有谁知道一个可靠的跨浏览器函数来获取从 keydown
事件中输入的字符吗?我可以从 quirksmode 网格写一个,但我不太想为这么简单却又不标准的事情重新发明轮子
Let me clarify:
让我澄清一下
There is no way to do this simply using event.keyCode
or event.which
. The overall logic is something like:
没有简单的方法可以仅使用 event.keyCode
或 event.which
来实现。整体逻辑大致如下
- get keycode 获取键码
- detect shift, ctrl 检测 Shift 和 Ctrl 键
- if ctrl, ignore 如果按下 Ctrl 键,忽略它
- create map of keycodes with and without shift key 创建一个包含 Shift 键和不包含 Shift 键的键码映射
- example map
{186 : ';', 187 : '=', 188 : ',', ....}
示例映射{186: ';', 187: '=', 188: ',', ....}
- need a separate map for shift key modifier 需要一个单独的映射来处理 Shift 键修饰符
- map needs to change depending on browser (especially Safari Mac which has keycodes like 60,000) 映射需要根据浏览器变化(特别是 Mac 上的 Safari,它有像 60,000 这样的键码)
- example map
- if keycode is in map, return mapped key 如果键码在映射中,返回映射的键
- if keycode is not in map, normalize numbers, apply shift modifier key if necessary, return
String.fromCharCode(key)
如果键码不在映射中,标准化数字,必要时应用 Shift 修饰键,返回String.fromCharCode(key)
It's not a simple solution, which is why I'm looking for a pre-made one :)
这不是一个简单的解决方案,这就是为什么我在寻找一个现成的解决方案 :)
问题解决:
Are you willing to use jQuery?
你愿意使用 jQuery 吗
$("input").bind("keydown",function(e){ var value = this.value + String.fromCharCode(e.keyCode); }
I believe that switching to the keypress event would solve the issue mentioned in your comment. Would the code below meet your requirments?
我相信切换到 keypress
事件可以解决你评论中提到的问题。下面的代码是否符合你的要求
$("input").bind("keypress",function(e){ var value = this.value + String.fromCharCode(e.keyCode); }