2012-09-03 21 views
31

Antes de marcar como duplicado, quiero que se den cuenta de que nadie ha proporcionado una buena respuesta para esta pregunta específica. En select all text in contenteditable div when it focus/click, la respuesta aceptada y la respuesta de Tim Down no son útiles, ya que solo funcionan cuando el elemento ya está enfocado. En mi caso, quiero que todo el texto en el div satisfactorio se seleccione después del clic de un botón, incluso si el div no se enfocó de antemano.¿Cómo seleccionar todo el texto en contenteditable div?

¿Cómo podría hacer esto?

Respuesta

46

que utiliza un código de this thread para llegar a mi respuesta. Es 100% jQuery como lo pediste también. Espero que les guste :)

jQuery.fn.selectText = function(){ 
    var doc = document; 
    var element = this[0]; 
    console.log(this, element); 
    if (doc.body.createTextRange) { 
     var range = document.body.createTextRange(); 
     range.moveToElementText(element); 
     range.select(); 
    } else if (window.getSelection) { 
     var selection = window.getSelection();   
     var range = document.createRange(); 
     range.selectNodeContents(element); 
     selection.removeAllRanges(); 
     selection.addRange(range); 
    } 
}; 

$("button").click(function() { 
    $("#editable").selectText(); 
});​ 

jsfiddle enlace.

+0

? compatibilidad del navegador en este – crush

+0

violín funciona en FF 28, pero no funciona en la entrada de 'elementos contenteditable' con OS theme (CSS' appearance') puede Quiere añadir 'element.focus (.),' 'a la selectText() 'función, o se seleccionará el texto sin el cursor estar en ese campo – CoDEmanX

+0

Sólo una sugerencia, quitar la línea " console.log (esto, elemento);", ya que no es necesario trabajar –

2
<div id="test" style=" border:solid 1px #D31444" contenteditable="true" onclick="document.execCommand('selectAll',false,null)">12 some text...</div> 

A juzgar por esta respuesta proporcionada en el enlace, no se puede usar el código al hacer clic dentro de su botón.

Lo dicho IM es decir incluso en el div onfocus="document.execCommand('selectAll',false,null)"

Entonces usar jQuery para activar el enfoque $('#test').focus();

9

Por ejemplo, en el próximo escenario si se ha ajustado el usuario enfoque en div editable (con el ratón, el teclado o haciendo clic en un botón) luego se selecciona el contenido de div editable.

<div id="editable" style=" border:solid 1px #D31444" contenteditable="true" 
 
    onfocus="document.execCommand('selectAll', false, null);"> 
 
    12 some text... 
 
</div> 
 
    
 
<button onclick="document.getElementById('editable').focus();" >Click me</button>

En jsFiddle: http://jsfiddle.net/QKUZz/

+0

enlace jsFiddle favor – think123

+0

y no es allí una ¿Otra forma de no incluir 'execCommand'? – think123

+0

@ think123, ver el enlace en la respuesta actualizada. ¿Por qué no 'document.execCommand'? Otra forma (creo) requerida para usar los objetos 'selection' y' range'. –

3

gran función.

He adaptado para permitir la plena selección de texto a través de cualquier número de divs editables a través de una clase, si se hace clic directamente o por pestañas a:

$.fn.selectText = function(){ 
    var doc = document; 
    var element = this[0]; 
    //console.log(this, element); 
    if (doc.body.createTextRange) { 
     var range = document.body.createTextRange(); 
     range.moveToElementText(element); 
     range.select(); 
    } else if (window.getSelection) { 
     var selection = window.getSelection();   
     var range = document.createRange(); 
     range.selectNodeContents(element); 
     selection.removeAllRanges(); 
     selection.addRange(range); 
    } 
}; 

$(".editable").on("focus", function() { 
    $(this).selectText(); 
}); 
$(".editable").on("click", function() { 
    $(this).selectText(); 
}); 
$('.editable').mouseup(function(e){ 
    e.stopPropagation(); 
    e.preventDefault(); 
    // maximize browser compatability 
    e.returnValue = false; 
    e.cancelBubble = true; 
    return false; 
}); 

HTML:

<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">01 text...</div> 
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">02 text...</div> 
<div class="editable" style="border:dotted 1px #ccc;" contenteditable="true">03 text...</div> 

FIDDLE :

http://jsfiddle.net/tw9jwjbv/

+0

gran función. , me salvó la vida. Agregué '$ (" # mybutton "). clic (función() { $ (" # mydiv ").elegir texto(); document.execCommand ("copiar"); 'que copia el contenido del DIV al portapapeles. – Matt

Cuestiones relacionadas