document explorer替代document.execCommand(" insertText",...),用于文本插入,可由用户撤消/重做 [英] internet explorer alternative to document.execCommand("insertText",...), for text insertion that can be undone/redone by the user

查看:1423
本文介绍了document explorer替代document.execCommand(" insertText",...),用于文本插入,可由用户撤消/重做的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户编辑 contenteditable div ,然后按某些键时,我想覆盖默认行为。
例如,我想在用户按ENTER时插入一个正常的换行符。
我这样做是使用 document.execCommand(insertText,...)

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,"\n");
        evt.preventDefault();
        evt.stopPropagation();
    }
}
</script>

此代码适用于chrome和firefox。但是,即不支持inserttext。是否有办法插入文本,即用户可以撤消它?

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?

推荐答案

IE 11有新的 ms -beginUndoUnit ms- endUndoUnit 命令。

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

我尝试过并且没能使用这些为IE 11创建工作解决方案。使用DOM范围和选择插入换行符很难;你可以更容易地做到这一点在IE中使用其遗留的 document.selection TextRange 对象但遗憾的是IE 11已删除 document.selection (但不是TextRange,奇怪的是)这使得它变得困难。在编写了令人讨厌的变通方法以从选择中创建TextRange之后,撤消无论如何都不起作用。以下是我的所作所为:

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

我决定再使用DOM Range和选择对象。换行插入代码是说明性的,不应该用于任何严重的事情,因为它涉及添加一个不间断的空间,以便将插入符号放在某处(尝试在< br>之后直接放置它)。 不起作用)。撤消会删除插入的内容,但遗憾的是不会移动插入符。

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/

这篇关于document explorer替代document.execCommand(&quot; insertText&quot;,...),用于文本插入,可由用户撤消/重做的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆