问题
I'm creating a complicated in-browser app and I'd like to use some keyboard shortcuts that are currently used by Chrome and/or the other major browsers. I searched online and couldn't find a way to override browser shortcuts, but I saw that Google Sheets has just the kind of functionality I want: a user can select an option to override browser shortcuts.
How does Google sheets make this work?
Update: To clarify, since this has gotten some downvotes: I'm aware of event.preventDefault(). The problem is that it does not seem to work for key combinations like Ctrl + t
(open new tab).
回答1:
The general idea is to intercept the event and call event.preventDefault()
on it if it corresponds to a shortcut that you want to override. For example, the following code will prevent you from navigating to your leftmost tab if you press control-1
:
document.body.addEventListener('keydown', (event) => {
// keyCode 49 corresponds to the "1" key
if(event.keyCode==49 && event.ctrlKey) {
event.preventDefault();
console.log('default action prevented, doing custom action instead');
}
});
body {
background-color: yellow;
}
click me first
Repeat for as many keyCodes and modifiers as you want.
来源:https://stackoverflow.com/questions/52774572/how-does-google-sheets-override-browser-shortcuts