可信的文本编辑器和光标位置

Cal*_*l S 6 html javascript jquery contenteditable

我怎么能(使用jquery或其他)在我的contenteditable div的光标/插入位置插入html:

<div contenteditable="true">Hello world</div>
Run Code Online (Sandbox Code Playgroud)

例如,如果光标/插入符号位于"hello"和"world"之间,则用户然后单击按钮,例如"插入图像",然后使用javascript,类似于<img src=etc etc>将插入"hello"和"world"之间.我希望我已经明确表示= S.

非常感谢示例代码,非常感谢!

Tim*_*own 10

以下函数将在所有主流桌面浏览器的光标位置插入DOM节点(元素或文本节点):

function insertNodeAtCursor(node) {
    var sel, range, html;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            sel.getRangeAt(0).insertNode(node);
        }
    } else if (document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        html = (node.nodeType == 3) ? node.data : node.outerHTML;
        range.pasteHTML(html);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您想要插入HTML字符串:

function insertHtmlAtCursor(html) {
    var sel, range, node;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.getRangeAt && sel.rangeCount) {
            range = window.getSelection().getRangeAt(0);
            node = range.createContextualFragment(html);
            range.insertNode(node);
        }
    } else if (document.selection && document.selection.createRange) {
        document.selection.createRange().pasteHTML(html);
    }
}
Run Code Online (Sandbox Code Playgroud)

我从我对类似问题的回答中对此进行了调整:如何在一个可疑的DIV中找到光标位置?


Zil*_*tel -1

我建议使用 jquery 插件a-tools

\n\n

该插件有七大功能:

\n\n
* getSelection \xe2\x80\x93 return start, end position, length of the selected text and the selected text. return start=end=caret position if text is not selected;\n* replaceSelection \xe2\x80\x93 replace selected text with a given string;\n* setSelection \xe2\x80\x93 select text in a given range (startPosition and endPosition);\n* countCharacters \xe2\x80\x93 count amount of all characters;\n* insertAtCaretPos \xe2\x80\x93 insert text at current caret position;\n* setCaretPos \xe2\x80\x93 set cursor at caret position (1 = beginning, -1 = end);\n* setMaxLength \xe2\x80\x93 set maximum length of input field. Also provides callback function if limit is reached. Note: The function has to have a number as input. Positive value for setting of limit and negative number for removing of limit.\n
Run Code Online (Sandbox Code Playgroud)\n\n

您需要的是insertAtCaretPos

\n\n
$("#textarea").insertAtCaretPos("<img src=etc etc>");\n
Run Code Online (Sandbox Code Playgroud)\n\n

可能有一个缺点:此插件仅适用于 textarea en input:text 元素,因此可能与 contenteditable 发生冲突。

\n

  • *“可能有一个缺点:此插件仅适用于 textarea en input:text 元素,因此可能与 contenteditable 发生冲突。”* 你是对的。根本行不通。 (2认同)