internet explorer alternative to document.execCommand(“insertText”,…), for text insertion that can be undone/redone by the user

前端 未结 2 1146
予麋鹿
予麋鹿 2020-12-17 18:22

When the user edits a contenteditable div, and press some keys, I would like to override the default behavior. For instance, I want to insert a normal line brea

2条回答
  •  醉话见心
    2020-12-17 18:35

    IE 11 has new ms-beginUndoUnit and ms-endUndoUnit commands.

    I tried and failed to create a working solution for IE 11 using these. Inserting a line break is hard with DOM ranges and selections; you can do it more easily in IE using its legacy document.selection and TextRange objects but unfortunately IE 11 removed document.selection (but not TextRange, strangely) which makes it difficult. After coding a nasty workaround to create a TextRange from the selection, undo didn't work anyway. Here's what I did:

    http://jsfiddle.net/E7sBD/2

    I decided to have another go using DOM Range and selection objects. The line break insertion code is illustrative and shouldn't be used for anything serious because it involves adding a non-breaking space to give the caret somewhere to go (trying to place it directly after the
    does not work). Undoing does remove the inserted content but unfortunately doesn't move the caret.

    http://jsfiddle.net/E7sBD/4/

提交回复
热议问题