问题
How can I in JavaScript detect the typing of a question mark on AZERTY keyboard ? On QWERTY keyboard a question mark produces the code 191, but on AZERTY it seems to produce code 188 (comma on QWERTY). Or should I distinguish between both keyboards in JavaScript, but how ?
回答1:
The fastest solution I can think of is to compare the key with the actual question mark, so something like this would be a good solution.
document.addEventListener('keydown', function(event) {
if (event.key && event.key === '?') {
// your code goes here
}
}, true);
回答2:
If you want to detect the character being typed, use KeyboardEvent.key
, not KeyboardEvent.code
-- the key
property will contain either the character that was typed (like "?"
), or a string like "Shift"
or "ArrowUp"
for special keys. The location of the key on the keyboard won't affect the result.
$("#f").on("keydown", function(ev) {
$(this).val(ev.key);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="f" autocomplete="off">
来源:https://stackoverflow.com/questions/45624118/keycode-detection-on-azerty-vs-qwerty