¿Cómo puedo (usando jquery u otro) insertar html en la posición cursor / cursor de mi div satisfactorio?
Hello world
Por ejemplo, si el cursor / cursor estaba entre “hola” y “mundo” y el usuario hace clic en un botón, por ejemplo, “insertar imagen”, luego usando javascript, algo como
se insertaría entre “hola” “y” mundo “. Espero haber aclarado esto = S
El código de ejemplo sería muy apreciado, ¡muchas gracias!
La siguiente función insertará un nodo DOM (elemento o nodo de texto) en la posición del cursor en todos los navegadores principales de escritorio:
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); } }
Si prefieres insertar una cadena 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); } }
Lo he adaptado desde mi respuesta a una pregunta similar: ¿Cómo encontrar la posición del cursor en una DIV contenteditable?
Con contenteditable
debe usar execCommand
.
Pruebe document.execCommand('insertImage', false, 'https://stackoverflow.com/questions/2937975/contenteditable-text-editor-and-cursor-position/image.jpg')
o document.execCommand('insertHTML', false, '
. El segundo no funciona en IE más antiguo. ')
en este código, acabo de reemplazar el código html con (“) a (‘)
usa esta syntax:
$("div.second").html("your html code and replace with (")to(') ");
Yo recomendaría el uso del plugin jquery a-tools
Este plugin tiene siete funciones:
* 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.
El que necesitas es insertAtCaretPos :
$("#textarea").insertAtCaretPos("
");
Puede haber un inconveniente: estos complementos solo funcionan con textarea en input: elementos de texto, por lo que puede haber conflictos con contentable.