简体   繁体   English

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

[英]Insert text at caret in contenteditable div

I am using the following function to insert text where the cursor is: 我正在使用以下功能在光标所在的位置插入文本:

Live JSFIDDLE 现场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);
    }
}

Then I have: 然后我有:

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

However, when I click the span, the text appends not in the contenteditable (since it lost its focus) but within itself. 但是,当我单击跨度时,文本不会附加在contenteditable中(因为它失去了焦点),而是附加在其内部。

How can I fix this? 我怎样才能解决这个问题? I need to insert the text inside contenteditable where the cursor is, and if the cursor is not there, then the text should append at the end of the text inside contenteditable. 我需要将文本插入到contenteditable中光标所在的位置,如果光标不在其中,则该文本应附加在contenteditable中文本的末尾。

Honestly, the quickest solution would be to use CSS on the input button to make it look like whatever the span should be. 老实说,最快的解决方案是在输入按钮上使用CSS,以使其看起来像跨度一样。 Quick and dirty, but it works... 快速又肮脏,但是可以用...

Track the cursor position through out the entire process within the div. 在整个div内的整个过程中跟踪光标位置。 So when the user does leave it, you still have the cursor position saved so it puts the text where the cursor was last. 因此,当用户确实离开它时,您仍然保存了光标位置,因此它将文本放置在光标的最后位置。 If code is needed, just ask. 如果需要代码,只需询问。

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

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