问题
I have an interactive html5 canvas thing where sometimes users will want to undo their actions. I have the logic for doing that implemented, but I'm not sure of how to properly catch the "user wants to undo" event.
Currently, I just listen to keyboard events and interpret "CTRL+Z" as a request-to-undo, like this:
document.addEventListener("keydown", e => {
const Z_KEY = 90;
let isUndo = e.keyCode == Z_KEY && e.ctrlKey && !e.shiftKey;
if (isUndo) {
restore(revision.undo());
}
});
The problem is that the standard shortcut for undo-ing varies by OS, and there are totally orthogonal ways to trigger it (such as shaking your phone).
What I want is to somehow tell the browser that I'm supporting undo, and that it should forward all the crazy OS-specific ways of triggering undo to a method I specify. As things stand now, the browser has no idea the user is doing anything that would involve undo-ing. All the browser sees is a canvas being clicked on and drawn to.
Is there a standard way to ask the browser to catch all the undo events for me? In a future-proof way that keeps working even as vendors invent new undo actions? What about a hacky workaround? Or perhaps there's a library whose focus is to solve this particular problem?
Notes:
- This question differs from How to handle undo/redo event in javascript?. That one is asking about catching changes to an element, whereas I always know about any changes because my code is the one performing those changes.
- The question Listen to undo/redo event in contenteditable div is also about change-detection instead of implementing undo, and is limited to a particular type of element. I'm willing to use custom elements to make this work.
回答1:
There's no standard javascript way of hooking things like undo/redo as there is no specific event for them.
Maybe Mousetrap does what you want. It's a library for abstracting keyboard events in javascript and includes a way to do a generic [system modifier]+key
hotkey kind of thing.
That said, you'll probably need a button somewhere if you want mobile. (I'm not familiar with the shake-to-undo action. That seems like new age hippy nonsense. =P )
来源:https://stackoverflow.com/questions/36974808/asking-for-undo-redo-events-in-html-javascript