How to prevent the browser to override my keyBindings of ace editor?

最后都变了- 提交于 2019-12-11 08:01:52

问题


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 of e.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 of e.keyCode is that e.key will only work with English/Latin keyboard input so the key must be literally "d" while e.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!