6

contenteditable divのカーソル/キャレット位置に(jqueryまたはその他を使用して)htmlを挿入するにはどうすればよいですか:

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

たとえば、カーソル/キャレットが「hello」と「world」の間にあり、ユーザーが「insert image」などのボタンをクリックした場合、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);
    }
}

これを私の回答から同様の質問に適応させました: How to find cursor position in a contenteditable 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="" />')。2番目は古い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の使用をお勧めします

このプラグインには 7 つの機能があります。

* 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 に答える