2010-05-30 15 views
6

¿Cómo puedo (usando jQuery u otro) insertar código HTML en la posición del cursor/intercalación de mi div contenteditable:editor de texto contentEditable y el cursor de posición

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

Por ejemplo, si el cursor/intercalación fue entre "hola "y" mundo "y el usuario hizo clic en un botón, por ejemplo," insertar imagen ", y luego, mediante javascript, se insertó algo como <img src=etc etc> entre" hola "y" mundo ". Espero haber hecho esto claro = S

El código de ejemplo sería muy apreciado, ¡muchas gracias!

Respuesta

-1

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. 

la que se necesita es insertAtCaretPos:

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

No podría ser un inconveniente: estos complementos solo funcionan con la entrada textarea en: elementos de texto, por lo que puede haber conflictos de ingenio h contenteditable.

+2

* "Puede haber un inconveniente: estos complementos solo funcionan con la entrada textarea en: elementos de texto, por lo que puede haber conflictos con contentable." * Estás en lo correcto. No funcionará en absoluto. –

9

La siguiente función se inserte un nodo DOM (elemento o nodo de texto) en la posición del cursor en todos los principales navegadores 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 prefiere 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); 
    } 
} 

he adaptado esto desde my respuesta a una pregunta similar: How to find cursor position in a contenteditable DIV?

2

con contenteditable se debe utilizar execCommand .

Pruebe document.execCommand('insertImage', false, 'image.jpg') o document.execCommand('insertHTML', false, '<img src="image.jpg" alt="" />'). El segundo no funciona en IE más antiguo.

+0

Gracias - eso funciona muy bien en Chrome. Tuve que usar insertHTML para agregar etiquetas 'alt' a una imagen; InsertImage Falló. –

Cuestiones relacionadas