繁体   English   中英

在contenteditable div中的插入符号中插入文本

[英]Insert text at caret in contenteditable div

我正在使用以下功能在光标所在的位置插入文本:

现场JSFIDDLE

function pasteHtmlAtCaret(html) {
    var sel, range;
    if (window.getSelection) {
        // IE9 and non-IE
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            range.deleteContents();

            // Range.createContextualFragment() would be useful here but is
            // non-standard and not supported in all browsers (IE9, for one)
            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);

            // Preserve the selection
            if (lastNode) {
                range = range.cloneRange();
                range.setStartAfter(lastNode);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }
    } else if (document.selection && document.selection.type != "Control") {
        // IE < 9
        document.selection.createRange().pasteHTML(html);
    }
}

然后我有:

$("span").click(function() {
    pasteHtmlAtCaret("Some <b>random</b> text");
});

但是,当我单击跨度时,文本不会附加在contenteditable中(因为它失去了焦点),而是附加在其内部。

我怎样才能解决这个问题? 我需要将文本插入到contenteditable中光标所在的位置,如果光标不在其中,则该文本应附加在contenteditable中文本的末尾。

老实说,最快的解决方案是在输入按钮上使用CSS,以使其看起来像跨度一样。 快速又肮脏,但是可以用...

在整个div内的整个过程中跟踪光标位置。 因此,当用户确实离开它时,您仍然保存了光标位置,因此它将文本放置在光标的最后位置。 如果需要代码,只需询问。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM