问题
This question came up after i implemented the ace editor...
here is the link for that:
Ace editor, how to remove all keyBindings but one?
I have the ace editor, and thx to the for loop:
for (key in editor.keyBinding.$defaultHandler.commandKeyBinding) {
if (key !== "ctrl-d")
delete editor.keyBinding.$defaultHandler.commandKeyBinding[key];
}
I have my own keyBindings, and the ace editor has its own, witch i deleted, all but one, and that one is the CTRL+D to remove a line...
but, my browser has already the ctrl-d stuff on the bookmark, and i need now to prevent that, any ideas?
回答1:
I tested in ace-editor and default function seem to block default keyboard shortcuts on its own. but for the sake of answering your question, you can use an event listener for ctrl + d
and command + d
than use e.preventDefault()
and e.stopPropagation()
... now to how would you use it with ace-editor:
document.addEventListener("keydown", function(e) {
if (e.key.toLowerCase() == "d" && (navigator.platform.match("Mac") ? e.metaKey : e.ctrlKey)) {
editor.execCommand("removeline");
e.preventDefault();
e.stopPropagation();
}
}, false);
- notice how I used
e.key.toLowerCase() == "d"
instead ofe.keyCode == 68
... this is because KeyboardEvent.keyCode is now marked as deprecated so I used KeyboardEvent.key instead. the.toLowerCase()
is used so the shortcut work even when Caps Lock is toggled. - one downside of using
e.key
instead ofe.keyCode
is thate.key
will only work with English/Latin keyboard input so the key must be literally "d" whilee.keyCode
will work with other languages input like Arabic for example (ctrl + ي)... so you decide which one to use.
if you already removed the default binding/command for the wanted command mentioned here you can add it without its key binding like this:
editor.commands.addCommand({
name: "removeline",
exec: function(editor) { editor.removeLines(); },
scrollIntoView: "cursor",
multiSelectAction: "forEachLine"
});
- it's neccsarry for this command to exist so
editor.execCommand("removeline")
will work
来源:https://stackoverflow.com/questions/42412824/how-to-prevent-the-browser-to-override-my-keybindings-of-ace-editor