问题描述
我正在使用 document.execCommand()
构建一个带有可编辑iframe的所见即所得编辑器。现在我需要使用insertHTML
命令,该命令在Chrome和Firefox中完美运行,但当然它在Internet Explorer中不起作用:
I'm building a wysiwyg-editor with an editable iframe using document.execCommand()
. Now i need to use the "insertHTML"
command which works perfectly in Chrome and Firefox but of course it doesn't work in Internet Explorer:
function run() {
document.getElementById("target").focus();
document.execCommand("insertHTML", false, "<b>ins</b>");
}
<div contenteditable id="target">contenteditable</div>
<button onclick="run()">contenteditable.focus() + document.execCommand("insertHTML", false, "<b>ins</b>")</button>
这个问题的标准解决方案是什么?没关系,如果它只能在IE8中运行,但IE7支持也会很好。
What is the standard solution to this problem? It's okay if it only works in IE8 but IE7-support would be nice too.
推荐答案
在IE< = 10中,您可以使用 pasteHTML
方法表示选择的 TextRange
:
In IE <= 10 you can use the pasteHTML
method of the TextRange
representing the selection:
var doc = document.getElementById("your_iframe").contentWindow.document;
if (doc.selection && doc.selection.createRange) {
var range = doc.selection.createRange();
if (range.pasteHTML) {
range.pasteHTML("<b>Some bold text</b>");
}
}
更新
在IE 11中, document.selection
消失了, insertHTML
是仍然不受支持,因此您需要以下内容:
In IE 11, document.selection
is gone and insertHTML
is still not supported, so you'll need something like the following:
这篇关于Internet Explorer中的execCommand(“insertHTML”,...)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!