propiedades ejemplo bootstrap javascript html css textarea

javascript - ejemplo - ¿Hay alguna forma de tener una altura de "adaptación automática" de área de texto basada en el contenido al cargar la página?



textarea value html (10)

¿Qué hay de http://www.jacklmoore.com/autosize/ Drop Autosize en cualquier página web y debería funcionar? La fuente es breve y bien comentada si tienes curiosidad por cómo funciona.

// Example: $(document).ready(function(){ $(''textarea'').autosize(); });

Fuente: https://github.com/jackmoore/autosize

Demostración: http://www.jacklmoore.com/autosize/

¿Hay alguna forma a través de CSS o Javascript que establezca la altura del área de texto en función del contenido? ¿Tengo una altura codificada en mi CSS pero quería que tenga un valor predeterminado para que no haya una barra de desplazamiento vertical en la carga de la página?


Aquí hay una solución javascript pura. Sin jQuery, sin plugins, etc. DEMO .

¿Entonces, cómo funciona? Supongamos que tiene un tamaño de fuente predeterminado / altura de línea / etc. Bueno, tu área de texto tiene alrededor de 11 caracteres por ancho de 100px. Si podemos tener esto en cuenta, entonces podemos usar esta función.

function textareaSetSize(elem, width) { var length = elem.value.length; //about 11 characters per 100 pixels var estimatedLines = Math.round(length/(width/100*11)); //alert(''Estimated number of lines: '' + length); elem.style.width = width + ''px''; elem.rows = estimatedLines; }

Entonces..

var selector = document.getElementsByClassName(''textarea''); for(var i = 0; i < selector.length; i++) { selector[i].onkeyup = function(){ textareaSetSize(this, 400); }; }

html ...

<button id="reset">Empty</button> <textarea class="textarea" id="autosize"></textarea> <textarea class="textarea" id="autosize2"></textarea> <textarea class="textarea" id="autosize3"></textarea> <textarea class="textarea" id="autosize4"></textarea>

corriéndolo ...

textareaSetSize(ta, 500); textareaSetSize(ta2, 400); textareaSetSize(ta3, 400); textareaSetSize(ta4, 400);

Esta no es una solución perfecta, así que si ves una innovación, avísame.


El único css que uso a continuación en el área de textarea es su width , no es necesario establecer una height inicial. overflow no debería ser necesario, ya que el scrollHeight que se utilizará es:

una medida de la altura del contenido de un elemento, incluido el contenido no visible en la pantalla debido a un desbordamiento.

scrollHeight : MDN

Sin embargo, si desea trabajar con Internet Explorer, entonces es necesario usar el overflow: auto , de lo contrario, IE insiste en agregar una barra de desplazamiento vertical (aunque no haya nada para desplazarse).

Tenga en cuenta que tampoco es necesario especificar el width , pero es la propiedad que se establece más comúnmente en relación con este tema.

Este es el JavaScript necesario:

document.addEventListener("DOMContentLoaded", function(event) { var ta = document.getElementById(''ta''); ta.style.height = ta.scrollHeight + ''px''; });

Cuando el DOM ha cargado, la height del área de texto se establece en su scrollHeight .

Aquí está una página completa para la prueba:

<!DOCTYPE html> <html> <head> <title>Some Title</title> <style> textarea { width: 300px; overflow: auto; } </style> </head> <body> <textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea> <script> document.addEventListener("DOMContentLoaded", function(event) { var ta = document.getElementById(''ta''); ta.style.height = ta.scrollHeight + ''px''; }); </script> </body> </html>

Si es necesario, el código se puede aplicar a todas las áreas de texto en la página:

document.addEventListener("DOMContentLoaded", function(event) { var tas = document.getElementsByTagName(''textarea''); for (var i=0; i < tas.length; i++) { tas[i].style.height = tas[i].scrollHeight + ''px''; } });


No sé por qué, pero parece que mi motor de búsqueda me trajo otra solución (un tutorial de "Cómo hacer"):

http://www.sitepoint.com/build-auto-expanding-textarea-3/

EDITAR:

Aquí está el código ..

/** * TextAreaExpander plugin for jQuery * v1.0 * Expands or contracts a textarea height depending on the * quatity of content entered by the user in the box. * * By Craig Buckler, Optimalworks.net * * As featured on SitePoint.com: * http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/ * * Please use as you wish at your own risk. */ /** * Usage: * * From JavaScript, use: * $(<node>).TextAreaExpander(<minHeight>, <maxHeight>); * where: * <node> is the DOM node selector, e.g. "textarea" * <minHeight> is the minimum textarea height in pixels (optional) * <maxHeight> is the maximum textarea height in pixels (optional) * * Alternatively, in you HTML: * Assign a class of "expand" to any <textarea> tag. * e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea> * * Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height. * e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea> * The textarea will use an appropriate height between 50 and 200 pixels. */ (function($) { // jQuery plugin definition $.fn.TextAreaExpander = function(minHeight, maxHeight) { var hCheck = !($.browser.msie || $.browser.opera); // resize a textarea function ResizeTextarea(e) { // event or initialize element? e = e.target || e; // find content length and box width var vlen = e.value.length, ewidth = e.offsetWidth; if (vlen != e.valLength || ewidth != e.boxWidth) { if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px"; var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax)); e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden"); e.style.height = h + "px"; e.valLength = vlen; e.boxWidth = ewidth; } return true; }; // initialize this.each(function() { // is a textarea? if (this.nodeName.toLowerCase() != "textarea") return; // set height restrictions var p = this.className.match(/expand(/d+)/-*(/d+)*/i); this.expandMin = minHeight || (p ? parseInt(''0''+p[1], 10) : 0); this.expandMax = maxHeight || (p ? parseInt(''0''+p[2], 10) : 99999); // initial resize ResizeTextarea(this); // zero vertical padding and add events if (!this.Initialized) { this.Initialized = true; $(this).css("padding-top", 0).css("padding-bottom", 0); $(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea); } }); return this; }; })(jQuery); // initialize all expanding textareas jQuery(document).ready(function() { jQuery("textarea[class*=expand]").TextAreaExpander(); });

Dejé los comentarios en el código ya que no es mi trabajo;)


Oye, puedes ir con el complemento ExpandingTextArea en el que se mantiene un elemento de clonación invisible detrás de tu área de texto. Cada vez que se modifica la altura de este pre, se actualiza el área de texto.

Es simple, simplemente incluya "expansion.js" y "jQuery" en su página y agregue la clase "expandiendo" al área de texto a la que necesita expandirse.

<script src=''expanding.js''></script> <textarea class=''expanding''></textarea>

Siga el enlace para más detalles y Demo.

Nota: Funcionará en la carga de documentos para textos ya añadidos.


Puede usar el complemento de cambio de tamaño automático utilizando jQuery UI Autoresize

Aquí está el html,

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script> <script src="http://css-tricks.com/examples/TextareaTricks/js/autoresize.jquery.min.js"></script> <textarea></textarea>

y aquí está el jQuery,

$(''textarea'').autoResize();

ver DEMO


Si no te importa una barra de desplazamiento dentro del área de texto, puedes usar

$(document).ready(function(){ tx = $(''#textarea'') tx.height(tx.prop(''scrollHeight'')); })

y aquí hay un Fiddle

otro Fiddle este tiene mínimo y máximo ancho establecido.

pero con plug-ins como http://www.jacklmoore.com/autosize/

la altura del cuadro de texto aumenta con la entrada.

o puedes probar este plug-in


Sin plugins podrías hacer algo como

$(document).ready(function(){ elem=document.getElementById(''#elemid''); while(elem.clientHeight < elem.scrollHeight) {elem.height(elem.height()+10)} });

Cambiar el tamaño del área de texto mientras tiene una barra de desplazamiento (por lo tanto, elem.clientHeight <elem.scrollHeight). Puede hacerlo con bastante facilidad, incluso sin JQuery, en JavaScript simple.

No probé el código, es solo el "concepto".

EDIT: Dumb me, es mucho más fácil, sin bucles ...

if (elem.clientHeight < elem.scrollHeight) elem.style.height=elem.scrollHeight+"px";


Probado en cromo

Solución javascript pura (sin plugin, sin jQuery)

en acción: fiddle

Creé 3 funciones:

  • obtener la altura de la línea
  • obtener numero de lineas
  • establecer la altura de área de texto a medida que escribe ( evento de entrada )

//attach input event document.getElementById(''ta'').addEventListener(''input'', autoHeight, false); function autoHeight(e){ var lh = getLineHeightInPixels(e.target); var nol = getNumberOfLines(e.target); var ht = lh * nol; e.target.style.height = ht + ''px''; } function getNumberOfLines(el){ var text = el.value var lines = text.split(//r|/r/n|/n/); return lines.length; } function getLineHeightInPixels(el){ var tempDiv = document.createElement(''div''); tempDiv.style.visibility = ''hidden''; tempDiv.style.fontFamily = getComputedStyle(el).getPropertyValue(''font-family''); tempDiv.style.fontSize = getComputedStyle(el).getPropertyValue(''font-size''); tempDiv.style.lineHeight = getComputedStyle(el).getPropertyValue(''line-height''); tempDiv.style.fontVariant = getComputedStyle(el).getPropertyValue(''font-variant''); tempDiv.style.fontStyle = getComputedStyle(el).getPropertyValue(''font-style''); tempDiv.innerText = ''abcdefghijklmnopqrstuwxyz''; document.documentElement.appendChild(tempDiv); var ht = parseInt(getComputedStyle(tempDiv).getPropertyValue(''height'')) document.documentElement.removeChild(tempDiv); return (ht); } //set height on document load document.addEventListener(''DOMContentLoaded'', function(){document.getElementById(''ta'').style.height = getLineHeightInPixels(document.getElementById(''ta'')) + ''px'';}, false);

<textarea id="ta"></textarea>


Una buena solución

JSFiddle

HTML

<div id="container"> <textarea > 1 12 123 1234 12345 123456 1234567 </textarea> </div>

CSS

div#container textarea { overflow-y: hidden; /* prevents scroll bar flash */ padding-top: 1.1em; /* prevents text jump on Enter keypress */ }

JQuery

// auto adjust the height of $(''#container'').on( ''keyup'', ''textarea'', function (e){ $(this).css(''height'', ''auto'' ); $(this).height( this.scrollHeight ); }); $(''#container'').find( ''textarea'' ).keyup();