次のようなことができます
fn
次のようなパラメーターを取る関数でjquerysプロパティを拡張します
検証関数を書く
- keyCode を文字列に変換します
- 正規表現と照合します。
- shiftキーが押された場合
- Ctrl/Alt キーが押されたなど、他の条件が満たされているかどうかを確認します。
- 結果を返します。
- 検証が成功した場合
コードサイトでは、これは好きかもしれません
$.fn.selectedKey = function (cb, data) {
def.call(data, {
ctrlKey: 2, //0: musn't be pressed, 1: must be pressed, 2: both.
altKey: 2, // "
invert: 0, //inverts the filter
filter: /.*/, // A Regular Expression, or a String with a Regular Expression
preventDefault: false //Set to true to prevent Default.
}); //Sets the default Data for the values used,
function validate(e) {
var key = e.char = String.fromCharCode(e.keyCode || e.which); // Converts the pressed key to a String
if (e.shiftKey) key = key.toUpperCase(); //Handles Case Sensitivity.
var exp = new RegExp(e.data.filter.replace(/\\\\(\d)/g, String.fromCharCode("$1"))); //Creates a new RegExp from a String to e.g. allow "\2" to match the keyCode 2
var c = !! (e.data.ctrlKey ^ e.ctrlKey ^ 1 > 0); //c == true if the above stated conditions are met e.g Ctrl Key Pressed and `ctrlKey == 1` -> true
var a = !! (e.data.altKey ^ e.altKey ^ 1 > 0); //e.g Alt Key Pressed and `altKey == 0` -> false
return (exp.test(key) && (c && a)); //Returns the validation Result
}
function def(obj) { //a minimal helper for default values
for (var prop in obj) {
this[prop] = this[prop] || obj[prop];
}
}
this.keypress(data, function (e) {
if (e.data.preventDefault) e.preventDefault();
if (validate(e) != e.data.invert) cb(e); //Calls the callback function if the conditions are met
});
};
次に、次の方法を使用できます
正規表現で
$("body").selectedKey(function (e) {
console.log("All lower characters Numbers and 'A': " + e.char);
}, {
filter: /[a-z]|[0-9]|A/,
ctrlKey: 2,
altKey: 2
});
これは、ctrl と alt の状態に関係なく、[az] または [0-9] または Shift キー + A が押された場合にトリガーされます。
またはキーコード
$("body").selectedKey(function (e) {
// do somet
console.log("KeyCode 2 " + e.char);
}, {
filter: "\\2", //Ctrl + b
ctrlKey: 1,
altKey: 2
});
ctrl + b を押すとトリガーされます
これらの両方を組み合わせることもできます。
Heres on JSBinの例をいじってみましょう。