2011-03-05 23 views
11

El siguiente script inserta texto al final del área de texto. Necesito cambiar a insertar texto después de la posición actual del cursor en el área de texto.Insertar texto después de la posición del cursor en el texto es

jQuery(document).ready(function($){ 
    $('#addCommentImage').click(function(){ 
     var imageLoc = prompt('Enter the Image URL:'); 
     if (imageLoc) { 
      $('#comment').val($('#comment').val() + '[img]' + imageLoc + '[/img]'); 
     } 
     return false; 
    }); 
}); 
+0

posible duplicado de [Insertar texto en textarea con jQuery] (http://stackoverflow.com/questions/946534/insert-text-into-textarea-with-jquery) – bummi

Respuesta

12

Usted puede retirar this answer. El plugin jquery insertAtCaret parece muy agradable.

+5

que en realidad se vincula a una versión que no funciona. El de arriba es el que quieres. Aquí está el violín http://jsfiddle.net/rmDzu/2/ – John

3

He modificado varias versiones de estos para obtener una versión que coloca el primer texto antes de lo que haya seleccionado y el segundo después de lo que ha seleccionado y mantener seleccionado lo que está seleccionado. Esto funciona en Chrome y FF, no en IE.

jQuery.fn.extend({ 
insertAtCaret: function(myValue, myValueE){ 
    return this.each(function(i) { 
    if (document.selection) { 
     //For browsers like Internet Explorer 
     this.focus(); 
     sel = document.selection.createRange(); 
     sel.text = myValue + myValueE; 
     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(startPos,endPos)+myValueE+this.value.substring(endPos,this.value.length); 
     this.focus(); 
     this.selectionStart = startPos + myValue.length; 
     this.selectionEnd = ((startPos + myValue.length) + this.value.substring(startPos,endPos).length); 
     this.scrollTop = scrollTop; 
    } else { 
     this.value += myValue; 
     this.focus(); 
    } 
    }) 
    } 
}); 

Uso: $('#box').insertAtCaret("[Before selection]", "[after]"); También: no reclamar esto como la mina de ninguna manera.

22

si el anterior no funciona (no lo hizo en mi caso - tal vez mi configuración es poco diferente), aquí es otra solución:

Se puede utilizar esta función de extensión para obtener la posición:

(function ($, undefined) { 
    $.fn.getCursorPosition = function() { 
     var el = $(this).get(0); 
     var pos = 0; 
     if ('selectionStart' in el) { 
      pos = el.selectionStart; 
     } else if ('selection' in document) { 
      el.focus(); 
      var Sel = document.selection.createRange(); 
      var SelLength = document.selection.createRange().text.length; 
      Sel.moveStart('character', -el.value.length); 
      pos = Sel.text.length - SelLength; 
     } 
     return pos; 
    } 
})(jQuery); 

el uso es: var position = $("#selector").getCursorPosition()

para insertar texto en la posición:

var content = $('#selector').val(); 
var newContent = content.substr(0, position) + "text to insert" + content.substr(position); 
$('#selector').val(newContent); 

Eso es todo.

+0

Gracias, muy útil para la implementación de Angular JS ya que las modificaciones de insertAtCaret() no funcionarán en caso de enlace ng-model. – Denis

+0

Funciona bien para insertar texto en la posición del cursor. Tenga en cuenta que si el usuario ha seleccionado algo de texto, lo insertará antes de la selección, en lugar de reemplazarlo (probado en Chrome). – rybo111

+0

función getCursorPosition cambiará a 'document.getElementById ('textarea'). SelectionStart;' o 'document.getElementById ('textarea'). SelectionEnd;' –

Cuestiones relacionadas