2012-04-19 26 views
23

Estoy tratando de agregar un fragmento de texto a un CKEditor existente usando jQuery. Esto debe hacerse cuando se hace clic en un enlace.Insertar texto en la posición del cursor a un CKEditor usando jQuery

he intentado esta solución, que trabaja para áreas de texto normales, pero no para CKEditor:

jQuery.fn.extend({ 
    insertAtCaret: function(myValue) { 
    return this.each(function(i) { 
     if (document.selection) { 
     //For browsers like Internet Explorer 
     this.focus(); 
     sel = document.selection.createRange(); 
     sel.text = myValue; 
     this.focus(); 
     } else if (this.selectionStart || this.selectionStart == '0') { 
     //For browsers like Firefox and Webkit based 
     var startPos = this.selectionStart; 
     var endPos = this.selectionEnd; 
     var scrollTop = this.scrollTop; 
     this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length); 
     this.focus(); 
     this.selectionStart = startPos + myValue.length; 
     this.selectionEnd = startPos + myValue.length; 
     this.scrollTop = scrollTop; 
     } else { 
     this.value += myValue; 
     this.focus(); 
     } 
    }) 
    } 
}); 

También hay una opción para utilizar: $('#editor').val(), pero esto añade el texto al final o al principio y no en el cursor.

Entonces, ¿hay alguna manera de lograr esto?

Respuesta

33

Debe utilizar este

$.fn.insertAtCaret = function (myValue) { 
    myValue = myValue.trim(); 
    CKEDITOR.instances['idofeditor'].insertText(myValue); 
}; 
+5

Gran! ¡Gracias! Hice un ligero cambio: 'CKEDITOR.instances [$ (this) .attr (" id ")]. InsertText (myValue);' así que no tengo que preocuparme por la identificación. – Phoenix

+0

aplausos !!! @Fénix – Devjosh

15

CKEditor tiene un mecanismo para insertar texto. Si actualiza directamente el textarea, está en efecto pasando por alto algunos de los mecanismos que CKEditor tiene para realizar un seguimiento de qué texto se ha ingresado. Prueba esto:

CKEDITOR.instances.IDofEditor.insertText('some text here'); 

More information here

3

pensé que debería mencionar que si está utilizando el adaptador de jQuery para CKEditor, puede introducir texto con jQuery esta manera los cuales se ve un poco más limpio.

$('textarea#id_body').ckeditor().editor.insertText('some text here'); 

o si va a insertar HTML

$('textarea#id_body').ckeditor().editor.insertHtml('<a href="#">text</a>'); 
Cuestiones relacionadas