String.fromCharCode not working on keydown event

你离开我真会死。 提交于 2019-12-12 18:25:13

问题


I am tyring to read the input characters on keydown event and try to process them. When I am triing to convert them into character using "String.fromCharCode(key);" Its always giving me the capital letters.

Upadte: Strangely the code works if I listen for "keypress" event. What is the reason for this. Could some one please explain this behavoir.

The sample code is given below:

var inp = document.getElementById("ti");

inp.addEventListener("keydown", onKeyDown);

function onKeyDown(e) {
    if (window.event) {
        var key = window.event.keyCode;
    } else {
        var key = e.keyCode;
    }
    document.getElementById("output").innerHTML +=  String.fromCharCode(key);
}

What is the best practice to read the character on keydown event

Fiddle Demo


回答1:


Guess you only need to change the EventListener to keypress

var inp = document.getElementById("ti");

inp.addEventListener("keypress", onKeyDown);

function onKeyDown(e) {
    if (window.event) {
        var key = window.event.keyCode;
    } else {
        var key = e.keyCode;
    }
    document.getElementById("output").innerHTML += String.fromCharCode(key);
}

Fiddle: http://jsfiddle.net/zZtW9/4/

Take a look here,you can note learn the differences from here : http://www.w3resource.com/html/attributes/HTML-event-attributes-completed.php

EDIT: For your doubt,check this : keyup event always return uppercase letter




回答2:


Try keypress instead of keydown

 inp.addEventListener("keypress", onKeyDown);

In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

DEMO




回答3:


I wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 inp.addEventListener("keydown", function(event) {
    var character = keysight(event).char
    document.getElementById("output").innerHTML +=  character
 })


来源:https://stackoverflow.com/questions/21726047/string-fromcharcode-not-working-on-keydown-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!