问题
I am enhancing (in an angular directive) the google places autocomplete input to select the first option if none is selected.
I am using the below code, which works like a charm when using "tab" or "enter" key.
Unfortunatly it is not working on android device (chrome) whith virtualkeyboard "next" key...
What could be the KeyCode of this "next" key as it is neither "tab" (9) or "enter" (13)
selectFirstOnEnterOrTab(input) {
// prevent submit on enter (13)
$(input).keydown(function (e) {
if (e.which === 13 && $('.pac-container:visible').length) {
return false;
}
});
// store the original event binding function
const _addEventListener = (input.addEventListener) ? input.addEventListener : input.attachEvent;
function addEventListenerWrapper(type, listener) {
// Simulate a 'down arrow' keypress on hitting 'return' when no pac suggestion is selected,
// and then trigger the original listener.
if (type === 'keydown') {
const orig_listener = listener;
listener = function (event) {
const suggestion_selected = $('.pac-item-selected').length > 0;
if ((event.which >= 9 && event.which <= 13) && !suggestion_selected) {
const simulated_downarrow = $.Event('keydown', {
keyCode: 40, which: 40
});
orig_listener.apply(input, [simulated_downarrow]);
}
orig_listener.apply(input, [event]);
};
}
_addEventListener.apply(input, [type, listener]); // add the modified listener
}
if (input.addEventListener) {
input.addEventListener = addEventListenerWrapper;
} else if (input.attachEvent) {
input.attachEvent = addEventListenerWrapper;
}
}
EDIT
Following Pitto suggestion, I have logged which and keycode on my android device, and for all the key I press, I receive 229, which apparently is a normal behaviour for android. Any ideas on how I can update my code for it to work on Android device too...
EDIT2
On android, on "next" pressed, there is no keydown event fired
回答1:
Can you try to set a minimal page with this code and see if it prints the right value?
document.body.addEventListener("keyup", function(event) {
console.log(event.key);
console.log(event.code);
});
Or, even easier, you can get keycodes using this website:
https://keycode.info
The tab key data for my Samsung S10e, as returned by https://keycode.info:
event.key = Unidentified
event.location = 0
event.which = 229
event.code =
回答2:
As pointed out already, the value for e.which
/ e.keyCode
is going to be 229
and e.key
is going to be 'Unidentified'
. You can check that using https://keyjs.dev, where you will also find an explanation about virtual/mobile keyboards:
When using virtual/mobile keyboards, formally know as IME (Input-Method Editor), the W3C standard states that a KeyboardEvent's e.keyCode should be 229 and e.key should be "Unidentified".
The best option on mobile is probably just adding an expand/down arrow to the dropdown and let users open it manually if they want to.
来源:https://stackoverflow.com/questions/58081977/what-is-the-keycode-for-next-in-android-virtualkeyboard