这是我发现的:http://jsfiddle.net/jwvha/211/
这个示例在跨浏览器(IE6~IE10、Chrome、Firefox 等)中运行良好。
我已将其修改为在 iFrame 中工作,这是我的大致代码:
insertHtml : function(html){
iframe.contentWindow.focus()
var sel, range;
if (iframe.contentWindow.getSelection) {
sel = iframe.contentWindow.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while (node = el.firstChild) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (iframeDocument.selection && iframeDocument.selection.type != "Control") {
// IE < 9
iframeDocument.selection.createRange().pasteHTML(html);
}
}
这在 IE6 - IE8 中运行良好,但在 IE9 和 IE10 中我收到以下错误:
SCRIPT5022: WrongDocumentError
在这一行:range.insertNode(frag);
我不知道为什么会发生这种情况,也不知道如何解决,所以我不得不用我蹩脚的英语来寻求帮助。
最佳答案
听起来您正在针对当前文档创建新的片段,然后尝试将其附加到 IFrame。尝试像这样创建元素:
var el = iframe.contentDocument.createElement("div");
el.innerHTML = html;
var frag = iframe.contentDocument.createDocumentFragment(), node, lastNode;
关于javascript - 在 iframe 中的光标处插入 html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16832061/