keydown
jQuery の関数によって呼び出されるハンドラー内からテキスト フィールドに入力された文字を特定する必要があります。key.which
キーコードのみが表示されますが、どの ASCII 文字がkey
表すかを把握する必要があります。どうすればいいですか?
5 に答える
イベントは、keyPress
入力された文字を取得するために必要なものです。(以下の keydown イベントの回避策を参照してください)。
keydown
keyup
どのキーが押されたかを示すコードを提供し、どのkeypress
文字が入力されたかを示します。
jQuerye.which
を使用するとキー コードを取得でき、String.fromCharCodeを使用すると、押された特定の文字 (を含むshiftKey) を取得できます。
デモ: http://jsfiddle.net/9TyzP/3
コード:
element.on ('keypress', function (e) {
console.log(String.fromCharCode(e.which));
})
注: jQuery と呼んだのは
e.which
、ブラウザーが異なれば、この情報を格納するために異なるプロパティを使用するためです。jQuery は.which
プロパティを正規化するため、確実に使用してキー コードを取得できます。
の回避策keydown
ただし、押された文字を動作させる簡単な回避策を書くことができkeydown
ます。回避策は、シフト キーを押さずに charCode としてキーを持つオブジェクトを作成し、値はシフト キーを使用することです。
注: @Sajjan Sarkarが指摘したようにe.which
、異なるブラウザーから返されるキーコード値にはいくつかの違いがあります。詳細はこちら
クロス ブラウザーの keyCode 値を正規化するために DEMO コードを更新しました。IE 8、FF、および Chrome でテストおよび検証済み。
以下の完全なコードと更新されたデモ: http://jsfiddle.net/S2dyB/17/
$(function() {
var _to_ascii = {
'188': '44',
'109': '45',
'190': '46',
'191': '47',
'192': '96',
'220': '92',
'222': '39',
'221': '93',
'219': '91',
'173': '45',
'187': '61', //IE Key codes
'186': '59', //IE Key codes
'189': '45' //IE Key codes
}
var shiftUps = {
"96": "~",
"49": "!",
"50": "@",
"51": "#",
"52": "$",
"53": "%",
"54": "^",
"55": "&",
"56": "*",
"57": "(",
"48": ")",
"45": "_",
"61": "+",
"91": "{",
"93": "}",
"92": "|",
"59": ":",
"39": "\"",
"44": "<",
"46": ">",
"47": "?"
};
$(element).on('keydown', function(e) {
var c = e.which;
//normalize keyCode
if (_to_ascii.hasOwnProperty(c)) {
c = _to_ascii[c];
}
if (!e.shiftKey && (c >= 65 && c <= 90)) {
c = String.fromCharCode(c + 32);
} else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
//get shifted keyCode value
c = shiftUps[c];
} else {
c = String.fromCharCode(c);
}
//$(element).val(c);
}).on('keypress', function(e) {
//$(element).val(String.fromCharCode(e.which));
});
});
キーボード イベントの詳細 --
ユーザーがキーを押すと、keydown、keypress、および keyup イベントが発生します。
keydownユーザーがキーを押したときに発生します。ユーザーがキーを押したままにしている間、これが繰り返されます。
keypress実際の文字がテキスト入力などに挿入されたときに発生します。ユーザーがキーを押したままにしている間、これが繰り返されます。
keyupキーのデフォルト アクションが実行された後、ユーザーがキーを離したときに発生します。
キーが最初に押されると、keydown
イベントが送信されます。キーが修飾キーでない場合、keypress
イベントが送信されます。ユーザーがキーを離すと、keyup
イベントが送信されます。
キーを押し続けると、オートリピートが始まります。これにより、次のような一連のイベントが送出されます。
keydown
keypress
keydown
keypress
<<repeating until the user releases the key>>
keyup
デモ: http://jsfiddle.net/9TyzP/1/
キーアップ、キーダウン vs キープレス
keydown イベントと keyup イベントは、キーが押されたり離されたりしたことを表し、keypress イベントは文字が入力されたことを表します。
デモ: http://jsfiddle.net/9TyzP/
参考文献:
文字入力の場合はkeypress()
、押された文字の実際の ASCII コードを報告する を使用することをお勧めします。自動的に大文字と小文字が区別され、文字以外のプレスは無視されます。いずれの場合も、 fromCharCode() を使用して文字列表現に変換できます。例えば
var c = String.fromCharCode(e.which) // or e.keyCode
keydown()
forとの場合は、状態keyup()
を使用してケースを追跡する必要があることを覚えておいてください。e.shiftKey
Selvakumar Arumugamの答えは、私にとって魅力のように機能します...テンキーをテストするまでは。ここでマイナーアップデート:
$(document).on('keydown', function(e) {
var c = e.which;
if (_to_ascii.hasOwnProperty(c)) {
c = _to_ascii[c];
}
if (!e.shiftKey && (c >= 65 && c <= 90)) {
c = String.fromCharCode(c + 32);
} else if (e.shiftKey && shiftUps.hasOwnProperty(c)) {
c = shiftUps[c];
} else if (96 <= c && c <= 105) {
c = String.fromCharCode(c - 48);
}else {
c = String.fromCharCode(c);
}
$kd.val(c);
})
grをen文字に変換するために上記のjavascriptクラスを作成して使用します。より多くの言語で使用できます。ユーザーから押された値を変更するためにJQueryを使用します。
var CharMapper = function (selector) {
this.getLanguageMapper = function (languageSource, languageTarget) {
// Check if the map is already defined.
if (typeof langugageCharMap === "undefined") {
langugageCharMap = {};
}
if (typeof langugageCharMap[languageSource] === "undefined") {
langugageCharMap[languageSource] = {};
}
// Initialize or get the language mapper.
if (typeof langugageCharMap[languageSource][languageTarget] === "undefined") {
switch (languageSource) {
case "GR":
switch (languageTarget) {
case "EN":
langugageCharMap[languageSource][languageTarget] = {
"α": "a", "ά": "a", "β": "b", "γ": "g", "δ": "d", "ε": "e", "έ": "e", "ζ": "z", "η": "h", "ή": "h", "θ": "th", "ι": "i", "ί": "i", "ϊ": "i", "ΐ": "i", "κ": "k", "λ": "l", "μ": "m", "ν": "n", "ξ": "ks", "ο": "o", "ό": "o", "π": "p", "ρ": "r", "σ": "s", "ς": "s", "τ": "t", "υ": "y", "ύ": "y", "ϋ": "y", "ΰ": "y", "φ": "f", "χ": "x", "ψ": "ps", "ω": "o", "ώ": "o", "Α": "A", "Ά": "A", "Β": "B", "Γ": "G", "Δ": "D", "Ε": "E", "Έ": "E", "Ζ": "Z", "Η": "H", "Ή": "H", "Θ": "TH", "Ι": "I", "Ί": "I", "Ϊ": "I", "Κ": "K", "Λ": "L", "Μ": "M", "Ν": "N", "Ξ": "KS", "Ο": "O", "Ό": "O", "Π": "P", "Ρ": "R", "Σ": "S", "Τ": "T", "Υ": "Y", "Ύ": "Y", "Ϋ": "Y", "Φ": "F", "Χ": "X", "Ψ": "PS", "Ω": "O", "Ώ": "O"
};
break;
case "GR":
default:
throw "Language(" + languageTarget + ") is not supported as target for Language(" + languageSource + ").";
}
break;
case "EN":
default:
throw "Language(" + languageSource + ") is not supported as source.";
}
}
return langugageCharMap[languageSource][languageTarget];
};
// Check the existance of the attribute.
var items = $(selector).find("*[data-mapkey]");
if (items.length === 0) {
return;
}
// For each item.
for (var i = 0; i < items.length; i++) {
var item = items[i];
// Get the source and target language.
var languages = $(item).attr("data-mapkey");
var languageSource = languages.split("_")[0];
var languageTarget = languages.split("_")[1];
// Add the event listener.
var self = this;
$(item).keypress(function (event) {
event.stopPropagation();
// Get the mapper to use.
var mapper = self.getLanguageMapper(languageSource, languageTarget);
// Get the key pressed.
var keyPressed = String.fromCharCode(event.which);
// Get the key to set. In case it doesn't exist in the mapper, get the key pressed.
var keyToSet = mapper[keyPressed] || keyPressed;
// Set the key to the dom.
this.value = this.value + keyToSet;
// Do not propagate.
return false;
});
}
};
例、
<input type="text" data-mapkey="GR_EN" />
<script type="text/javascript">
new CharMapper("body");
</script>