Javascript - jHtmlArea,设置光标位置

时间:2011-11-16 10:33:53

标签: javascript jhtmlarea

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

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

1 个答案:

答案 0 :(得分: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);
    }
}
相关问题