Unable to get document.execCommand('undo') working in the same manner across browsers

前端 未结 2 1972
青春惊慌失措
青春惊慌失措 2021-01-03 11:02

I have some code implementing a context menu on a textbox, the context menu is to have an Undo and Redo item that calls the browsers native methods

相关标签:
2条回答
  • 2021-01-03 11:26

    As I discovered from the question I asked, the undoManager API in Firefox DOES work. I looked at the jsFiddle link (http://jsfiddle.net/DULV4/1/) posted by Tim Down, and there appear to be a couple issues:

    • An undoScope attribute must be set to true (either in-line or programmatically). This enables the undoManager for that element.
    • Anything you undo has to first be created by the undoManager.transact() function (though I'm wondering if there is any way to incorporate the native undo stack into the current undoManager's transaction history).

    I'm only a novice with this, so take what I say with a grain of salt and see https://dvcs.w3.org/hg/undomanager/raw-file/tip/undomanager.html for all the information on using it.

    0 讨论(0)
  • 2021-01-03 11:42

    I don't think it's possible with document.execCommand(), in Firefox at least. You could make your own undo stack, or in future use the new UndoManager API (implemented in Firefox 20 but disabled by default).

    Here's an example of using your own undo stack by taking snapshots of the value and selection using the input event. You could improve this by merging consecutive typing events into a single undo item, for example. There is also some inconsistency between browsers with the caret position, but it's just a proof of concept.

    http://jsfiddle.net/FMSsL/

    Using the new DOM UndoManager API seems to be simple: if I understand it right and if the browser supports it, the <input> element will have an undoManager property, which is an object with undo() and redo() methods, so the task is as simple as

    document.getElementById("input").undoManager.undo();
    

    Unfortunately only Firefox 20 and above supports the UndoManager API and it's disabled by default. Even once it's enabled, the following demo does not work even though I think it should, so this option is some way off being viable.

    http://jsfiddle.net/DULV4/2/

    0 讨论(0)
提交回复
热议问题