Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

javascript - internet explorer alternative to document.execCommand("insertText",...), for text insertion that can be undone/redone by the user

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 break when the user press ENTER. I do that using document.execCommand("insertText",...)

This is the only way I have found so far to make this action undoable and redoable by the user.

<div id="editor" contenteditable="true" style="white-space:pre-wrap">
Some text....
</div>

<script>
$("#editor").keydown(function(evt){
    console.log(evt.keyCode);
    if(evt.keyCode==13){
        document.execCommand("insertText",false,"
");
        evt.preventDefault();
        evt.stopPropagation();
    }
}
</script>

This code works well on chrome and firefox. But, ie does not support "inserttext". Would there be a way to insert text with ie, such that the user can undo it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 <br> does not work). Undoing does remove the inserted content but unfortunately doesn't move the caret.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...