开发者

get character typed, cross-browser

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.

Let me clarify:

There is no way to do this simply using event.keyCode or event.which. The overall logic is something like:

  • get keycode
  • detect shift, ctrl
  • if ctrl, ignore
  • create map of keycodes with and without shift key
    • example map {186 : ';', 187 : '=', 188 : ',', ....}
    • need a seperate map for shift key modifier
    • map needs to change depending on browser (especially Safari Mac which has ke开发者_Go百科ycodes like 60,000)
  • 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)

It's not a simple solution, which is why I'm looking for a pre-made one :)


Are you willing to use 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?

$("input").bind("keypress",function(e){ var value = this.value + String.fromCharCode(e.keyCode); }


I've been wondering the same thing for years. Recently I got fed up with having to look up keycodes for events that I wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 element.addEventListener("keydown", function(event) {
    var character = keysight(event).char
 })

It doesn't ignore anything on ctrl, so you'd have to do that manually if you want. But it does all the rest of the logic you gave.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜