Я ответил на похожий вопрос вчера. Обратите внимание, что вы должны использовать событие keypress
для всего, что связано с персонажем; keydown
не подойдет.
Я бы сказал, что Enter , кстати, можно печатать, и эта функция считает, что это так. Если вы не согласны, вы можете изменить его, чтобы отфильтровать нажатия клавиш, указав для свойства which
или keyCode
события значение 13.
function isCharacterKeyPress(evt) {
if (typeof evt.which == "undefined") {
// This is IE, which only fires keypress events for printable keys
return true;
} else if (typeof evt.which == "number" && evt.which > 0) {
// In other browsers except old versions of WebKit, evt.which is
// only greater than zero if the keypress is a printable key.
// We need to filter out backspace and ctrl/alt/meta key combinations
return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
}
return false;
}
var input = document.getElementById("your_input_id");
input.onkeypress = function(evt) {
evt = evt || window.event;
if (isCharacterKeyPress(evt)) {
// Do your stuff here
alert("Character!");
}
});