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