6

我如何(使用 jquery 或其他)在我的 contenteditable div 的光标/插入符号位置插入 html:

<div contenteditable="true">Hello world</div>

例如,如果光标/插入符号在“hello”和“world”之间,然后用户单击了一个按钮,例如“插入图像”,那么使用 javascript,<img src=etc etc>将在“hello”和“world”之间插入类似的东西。我希望我已经说清楚了=S

示例代码将不胜感激,非常感谢!

4

4 回答 4

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);
    }
}

如果您希望插入 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);
    }
}

我已经根据我对类似问题的回答对此进行了调整:如何在可内容编辑的 DIV 中找到光标位置?

于 2010-05-30T16:36:18.603 回答
2

contenteditable你应该使用execCommand.

尝试document.execCommand('insertImage', false, 'image.jpg')document.execCommand('insertHTML', false, '<img src="image.jpg" alt="" />')。第二个在较旧的 IE 中不起作用。

于 2012-03-05T22:28:13.467 回答
0

在这段代码中,我只是将 html 代码替换为(")(')

使用这个语法:

$("div.second").html("your html code and replace with (")to(')  ");
于 2018-08-04T12:37:13.503 回答
-1

我建议使用 jquery 插件a-tools

这个插件有七个功能:

* getSelection – return start, end position, length of the selected text and the selected text. return start=end=caret position if text is not selected;
* replaceSelection – replace selected text with a given string;
* setSelection – select text in a given range (startPosition and endPosition);
* countCharacters – count amount of all characters;
* insertAtCaretPos – insert text at current caret position;
* setCaretPos – set cursor at caret position (1 = beginning, -1 = end);
* setMaxLength – 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.

您需要的是insertAtCaretPos

$("#textarea").insertAtCaretPos("<img src=etc etc>");

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

于 2010-05-30T08:49:33.807 回答