Można zrobić coś
Extend jquerys fn
propertie z funkcji, która zajmuje params jak
- Niektóre dane
- funkcji zwrotnej
napisać funkcję walidacji które
- konwertuje keyCode do String
- dopasować go przed wyrażeniem regularnym.
- Jeśli shiftKey został naciśnięty
- przekonwertować go na wielkie litery
- sprawdzić czy innych warunkach jak klawisz Ctrl/Alt naciśnięty są spełnione.
- Powoduje zwrócenie wyniku.
- Jeśli walidacja powiedzie
- wykonać funkcję oddzwonienia
Na stronie kodu może to podoba
$.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
});
};
które można następnie użyć następujące sposoby
Z regex
$("body").selectedKey(function (e) {
console.log("All lower characters Numbers and 'A': " + e.char);
}, {
filter: /[a-z]|[0-9]|A/,
ctrlKey: 2,
altKey: 2
});
To byłby uruchomiony, jeżeli każdy [AZ] lub [0-9] lub klawisz Shift + A został naciśnięty, niezależnie od stanu Ctrl i Alt
Albo keycode
$("body").selectedKey(function (e) {
// do somet
console.log("KeyCode 2 " + e.char);
}, {
filter: "\\2", //Ctrl + b
ctrlKey: 1,
altKey: 2
});
byłby uruchamiany po naciśnięciu ctrl + b
Można również połączyć oba.
Oto przykład na temat JSBin, w którym można się bawić.
Świetnie, dziękuję – ted