1

我正在使用 jHtmlArea,但我猜这个问题与使用 iframe/文档编辑模式运行的任何 html 文本框有关。

使用 pasteHTML 函数将一些文本设置到 jHtmlArea 中后,我想将光标放在我插入的文本之后,有没有很好的方法来做到这一点?

4

1 回答 1

2

我建议将 jHtmlArea 的pasteHTML实现替换为不使用浏览器嗅探的称职的实现,在浏览器之间的行为一致,并将插入符号放在为您插入的内容之后。类似于以下内容,改编自我在这里的回答:Insert html at caret in a contenteditable div

jHtmlArea.prototype.pasteHTML = function(html) {
    var sel, range, iframe = this.iframe[0],
        win = iframe.contentWindow || iframe.contentDocument.defaultView,
        doc = win.document;

    win.focus();
    if (win.getSelection) {
        // IE9 and non-IE
        sel = win.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // not supported in all browsers (IE9, for one)
            var el = document.createElement("div");
            el.innerHTML = html;
            var frag = doc.createDocumentFragment(), node, lastNode;
            while ( (node = el.firstChild) ) {
                lastNode = frag.appendChild(node);
            }
            range.insertNode(frag);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        // IE < 9
        sel.createRange().pasteHTML(html);
    }
}
于 2011-11-16T12:02:48.120 回答