在iframe的光标处插入html

Insert html at cursor in a iframe

本文关键字:插入 html 光标 iframe      更新时间:2023-09-26

我发现: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);

我不知道为什么会发生这种情况,也不知道如何解决,所以我不得不用我蹩脚的英语寻求帮助。

听起来就像您正在针对当前文档创建新的Fragment,然后尝试将其附加到IFrame。试着像这样创建元素:

var el = iframe.contentDocument.createElement("div");
el.innerHTML = html;
var frag = iframe.contentDocument.createDocumentFragment(), node, lastNode;