Crear un área de texto con redimensionamiento automático


Hubo otro hilo sobre esto, que he intentado. Pero hay un problema: el textarea no se reduce si elimina el contenido. No puedo encontrar ninguna manera de reducirlo al tamaño correcto - el valor clientHeight vuelve como el tamaño completo del textarea, no su contenido.

El código de esa página está abajo:

function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}

window.onload = function() {
    document.getElementById("ta").onkeyup = function() {
      FitToContent( this, 500 )
    };
}
Author: Racil Hilan, 2009-01-18

30 answers

Esto funciona para mí (Firefox 3.6 / 4.0 y Chrome 10/11):

var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on'+event, handler);
    };
}
else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function init () {
    var text = document.getElementById('text');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
}
textarea {
    border: 0 none white;
    overflow: hidden;
    padding: 0;
    outline: none;
    background-color: #D0D0D0;
}
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>

Si quieres probarlo en jsfiddle Comienza con una sola línea y crece solo la cantidad exacta necesaria. Está bien para un solo textarea, pero quería escribir algo donde tendría muchos muchos muchos tales textareas (casi tanto como uno normalmente tendría líneas en un documento de texto grande). En ese caso es muy lento. (En Firefox es increíblemente lento.) Así que realmente me gustaría un enfoque que utiliza CSS puro. Esto sería posible con contenteditable, pero quiero que sea solo texto plano.

 175
Author: panzi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-09 19:30:32

UNA SOLUCIÓN COMPLETA PERO SIMPLE

Actualizado 23/08/2017 (Soporte mejorado del navegador para móviles y tabletas)

El siguiente código funcionará:

  • En la entrada de clave.
  • Con texto pegado (clic derecho & ctrl+v).
  • Con texto cortado (clic derecho & ctrl+x).
  • Con texto precargado.
  • Con todas las áreas de texto (cuadros de texto multilínea) en todo el sitio.
  • Con Firefox (v31-55 probado).
  • Con Cromo (v37-60 probado).
  • Con IE (v9-v11 probado).
  • Con Borde (v14-v15 probado).
  • Con IOS Safari.
  • Con Navegador Android.
  • Con JavaScript modo estricto.
  • Es w3c validado.
  • Y es ágil y eficiente.

OPCIÓN 1 (Con jQuery)

Este código se requiere jQuery y ha sido probado y está trabajando con 1.7.2 - 3.2.1

Simple (Agregue este código jquery a su archivo de script maestro y olvídelo.)

$('textarea').each(function () {
  this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
}).on('input', function () {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
});
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT.
This javascript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Prueba en jsfiddle


OPCIÓN 2 (JavaScript puro)

Simple (Agregue este JavaScript a su archivo de script maestro y olvídalo.)

var tx = document.getElementsByTagName('textarea');
for (var i = 0; i < tx.length; i++) {
  tx[i].setAttribute('style', 'height:' + (tx[i].scrollHeight) + 'px;overflow-y:hidden;');
  tx[i].addEventListener("input", OnInput, false);
}

function OnInput() {
  this.style.height = 'auto';
  this.style.height = (this.scrollHeight) + 'px';
}
<textarea placeholder="Type, paste, cut text here...">PRELOADED TEXT. This JavaScript should now add better support for IOS browsers and Android browsers.</textarea>
<textarea placeholder="Type, paste, cut text here..."></textarea>

Prueba en jsfiddle


OPCIÓN 3 (Extensión jQuery)

Útil si desea aplicar más encadenamiento a las áreas de texto que desea que sean de tamaño automático.

jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ 'height': 'auto', 'overflow-y': 'hidden' })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on('input', function() {
        autoHeight_(this);
      });
    });
  }
});

Invoca con $('textarea').autoHeight()


ACTUALIZANDO EL ÁREA DE TEXTO A TRAVÉS DE JAVASCRIPT

Al inyectar contenido en un área de texto a través de JavaScript, agregue el siguiente código para invocar la función en la opción 1.

$('textarea').trigger('input');
 234
Author: DreamTeK,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-23 13:01:31

Solución jQuery ajuste el css para que coincida con sus requisitos

Css...

div#container textarea {
    min-width: 270px;
    width: 270px;
    height: 22px;
    line-height: 24px;
    min-height: 22px;
    overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
    padding-top: 1.1em; /* fixes text jump on Enter keypress */
}

Javascript...

// auto adjust the height of
$('#container').delegate( 'textarea', 'keydown', function (){
    $(this).height( 0 );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keydown();

O alternativa para jQuery 1.7+...

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

He creado un violín con el estilo mínimo absoluto como punto de partida para sus experimentos... http://jsfiddle.net/53eAy/951 /

 61
Author: chim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-14 15:18:47
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Textarea autoresize</title>
    <style>
    textarea {
        overflow: hidden;
    }
    </style>
    <script>
    function resizeTextarea(ev) {
        this.style.height = '24px';
        this.style.height = this.scrollHeight + 12 + 'px';
    }

    var te = document.querySelector('textarea');
    te.addEventListener('input', resizeTextarea);
    </script>
</head>
<body>
    <textarea></textarea>
</body>
</html>

Probado en Firefox 14 y Chromium 18. Los números 24 y 12 son arbitrarios, prueba para ver lo que más te convenga.

Podría prescindir de las etiquetas de estilo y script, pero se vuelve un poco desordenado en mi humilde opinión (esto es HTML+JS de estilo antiguo y no se recomienda).

<textarea style="overflow: hidden" onkeyup="this.style.height='24px'; this.style.height = this.scrollHeight + 12 + 'px';"></textarea>

Editar: código modernizado. Se ha cambiado el atributo onkeyup a addEventListener.
Editar: keydown funciona mejor que keyup
Editar: declarar función antes de usar
Editar: la entrada funciona mejor que keydown (thnx @WASD42 & @MA-Maddin)

Jsfiddle

 28
Author: GijsjanB,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-09 09:55:44

La mejor solución (funciona y es corta) para mí es:

    $(document).on('input', 'textarea', function () {
        $(this).outerHeight(38).outerHeight(this.scrollHeight); // 38 or '1em' -min-height
    }); 

Funciona como un encanto sin parpadear con pasta (con el ratón también), cortar, entrar y se reduce al tamaño correcto.

Por favor, echa un vistazo a jsFiddle.

 21
Author: vatavale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-05 10:31:24

Estás usando el valor más alto del clientHeight actual y el content scrollHeight. Cuando se reduce el scrollHeight eliminando contenido, el área calculada no puede reducirse porque el clientHeight, previamente establecido por estilo.altura, lo mantiene abierto. En su lugar, podría tomar un max() de scrollHeight y un valor de altura mínima que haya predefinido o calculado a partir de textarea.filas.

En general, probablemente no debería confiar en scrollHeight en los controles de formulario. Aparte desde scrollHeight siendo tradicionalmente menos ampliamente soportado que algunas de las otras extensiones IE, HTML / CSS no dice nada acerca de cómo los controles de formulario se implementan internamente y no se garantiza scrollHeight será nada significativo. (Tradicionalmente, algunos navegadores han utilizado widgets del sistema operativo para la tarea, haciendo que la interacción CSS y DOM en sus internos sea imposible.) Al menos busca la existencia de scrollHeight/clientHeight antes de intentar habilitar el efecto.

Otra posible alternativa el enfoque para evitar el problema si es importante que funcione más ampliamente podría ser usar un div oculto con el mismo tamaño que el área de texto y establecido en la misma fuente. En keyup, copia el texto del área de texto a un nodo de texto en div oculto (recordando reemplazar '\n' con un salto de línea, y escapar '

 16
Author: bobince,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-01-18 00:57:13

Si no necesitas soportar IE8 puedes usar el evento input:

var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));

resizingTextareas.forEach(function(textarea) {
  textarea.addEventListener('input', autoresize, false);
});

function autoresize() {
  this.style.height = 'auto';
  this.style.height = this.scrollHeight+'px';
  this.scrollTop = this.scrollHeight;
  window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}

Ahora solo necesita agregar un poco de CSS y ya está:

textarea[autoresize] {
  display: block;
  overflow: hidden;
  resize: none;
}

Uso:

<textarea autoresize>Type here and I’ll resize.</textarea>

Puedes leer más sobre cómo funciona en mi entrada de blog.

 14
Author: We are hiring Elm and JS devs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-25 14:27:49

Autosize

Https://github.com/jackmoore/autosize

Solo funciona, independiente, es popular (3.0 k+ estrellas GitHub a partir de octubre de 2018), disponible en cdnjs) y ligero (~3.5 k). Demo:

<textarea id="autosize" style="width:200px;">a
J   b
c</textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js"></script>
<script>autosize(document.querySelectorAll('#autosize'));</script>

Por cierto, si está utilizando el editor ACE, use maxLines: Infinity: Ajustar automáticamente la altura al contenido en Ace Cloud 9 editor

 9
Author: Ciro Santilli 新疆改造中心 六四事件 法轮功,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-06 20:52:48

¿Alguien ha considerado contenteditable? Sin perder el tiempo con el desplazamiento, y el único JS que me gusta es si planea guardar los datos en blur... y al parecer, es compatible en todos los navegadores populares: http://caniuse.com/#feat=contenteditable

Simplemente dale estilo para que parezca un cuadro de texto, y se auto dimensiona... Haga su min-height la altura preferida del texto y tenga en él.

Lo bueno de este enfoque es que puede guardar y etiquetar algunos de los navegador.

Http://jsfiddle.net/gbutiri/v31o8xfo /

<style>
.autoheight {
    min-height: 16px;
    font-size: 16px;
    margin: 0;
    padding: 10px;
    font-family: Arial;
    line-height: 16px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    overflow: hidden;
    resize: none;
    border: 1px solid #ccc;
    outline: none;
    width: 200px;
}
</style>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
$(document).on('blur','.autoheight',function(e) {
    var $this = $(this);
    // The text is here. Do whatever you want with it.
    console.log($this.html());
});

</script>
<div class="autoheight contenteditable" contenteditable="true">Mickey Mouse</div>
 6
Author: Webmaster G,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-16 20:09:28

Utilicé el siguiente código para múltiples áreas de texto. Funciona bien en Chrome 12, Firefox 5 e IE 9, incluso con eliminar, cortar y pegar acciones realizadas en las áreas de texto.

<!-- language: lang-html -->
<style type='text/css'>
textarea { border:0 none; overflow:hidden; outline:none; background-color:#eee }
</style>
<textarea style='height:100px;font-family:arial' id="txt1"></textarea>
<textarea style='height:125px;font-family:arial' id="txt2"></textarea>
<textarea style='height:150px;font-family:arial' id="txt3"></textarea>
<textarea style='height:175px;font-family:arial' id="txt4"></textarea>
<script type='text/javascript'>
function attachAutoResizeEvents()
{   for(i=1;i<=4;i++)
    {   var txtX=document.getElementById('txt'+i)
        var minH=txtX.style.height.substr(0,txtX.style.height.indexOf('px'))
        txtX.onchange=new Function("resize(this,"+minH+")")
        txtX.onkeyup=new Function("resize(this,"+minH+")")
        txtX.onchange(txtX,minH)
    }
}
function resize(txtX,minH)
{   txtX.style.height = 'auto' // required when delete, cut or paste is performed
    txtX.style.height = txtX.scrollHeight+'px'
    if(txtX.scrollHeight<=minH)
        txtX.style.height = minH+'px'
}
window.onload=attachAutoResizeEvents
</script>
 4
Author: Nikunj Bhatt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-23 15:10:50

Los siguientes trabajos para cortar, pegar, etc., independientemente de si esas acciones son del ratón, un atajo de teclado, seleccionando una opción de una barra de menú ... varias respuestas adoptan un enfoque similar, pero no tienen en cuenta el tamaño de las cajas, por lo que aplican incorrectamente el estilo overflow: hidden.

Hago lo siguiente, que también funciona bien con max-height y rows para la altura mínima y máxima.

function adjust() {
  var style = this.currentStyle || window.getComputedStyle(this);
  var boxSizing = style.boxSizing === 'border-box'
      ? parseInt(style.borderBottomWidth, 10) +
        parseInt(style.borderTopWidth, 10)
      : 0;
  this.style.height = '';
  this.style.height = (this.scrollHeight + boxSizing) + 'px';
};

var textarea = document.getElementById("ta");
if ('onpropertychange' in textarea) { // IE
  textarea.onpropertychange = adjust;
} else if ('oninput' in textarea) {
  textarea.oninput = adjust;
}
setTimeout(adjust.bind(textarea));
textarea {
  resize: none;
  max-height: 150px;
  border: 1px solid #999;
  outline: none;
  font: 18px sans-serif;
  color: #333;
  width: 100%;
  padding: 8px 14px;
  box-sizing: border-box;
}
<textarea rows="3" id="ta">
Try adding several lines to this.
</textarea>

Para la integridad absoluta, deberías llamar a la función adjust en algunas circunstancias más:

  1. Eventos de redimensionamiento de ventanas, si el ancho del textarea cambia con el redimensionamiento de ventanas, u otros eventos que cambian el ancho del área de texto
  2. Cuando el atributo de estilo textarea's display cambia, por ejemplo, cuando pasa de none (oculto) a block
  3. Cuando el valor de textarea se cambia programáticamente

Tenga en cuenta que usar window.getComputedStyle o obtener currentStyle puede ser algo costoso computacionalmente, por lo tanto, es posible que desee almacenar en caché el resultado en su lugar.

Funciona para IE6, así que realmente espero que sea suficiente soporte.

 4
Author: Joseph Nields,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-24 17:14:43

Hay un enfoque ligeramente diferente.

<div style="position: relative">
  <pre style="white-space: pre-wrap; word-wrap: break-word"></pre>
  <textarea style="position: absolute; top: 0; left: 0; width: 100%; height: 100%"></textarea>
</div>

La idea es copiar el texto de textarea en el pre y CSS vamos a asegurarnos de que tengan el mismo tamaño.

El beneficio es que los frameworks presentan herramientas simples para mover texto sin tocar ningún evento. Es decir, en AngularJS se añadiría un ng-model="foo" ng-trim="false" a la textarea y ng-bind="foo + '\n'" a la pre. Véase un violín.

Solo asegúrese de que pre tenga el mismo tamaño de fuente que textarea.

 3
Author: Karolis Juodelė,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-17 14:45:33

Algunas correcciones. Funciona perfectamente en Opera

  $('textarea').bind('keyup keypress', function() {
      $(this).height('');
      var brCount = this.value.split('\n').length;
      this.rows = brCount+1; //++ To remove twitching
      var areaH = this.scrollHeight,
          lineHeight = $(this).css('line-height').replace('px',''),
          calcRows = Math.floor(areaH/lineHeight);
      this.rows = calcRows;
  });
 2
Author: artnik-pro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-19 12:29:54

Conozco una manera corta y correcta de implementar esto con jquery.No div extra oculto necesario y funciona en la mayoría de los navegadores

<script type="text/javascript">$(function(){
$("textarea").live("keyup keydown",function(){
var h=$(this);
h.height(60).height(h[0].scrollHeight);//where 60 is minimum height of textarea
});});

</script>
 2
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-24 08:46:12

No se si alguien menciona esto pero en algunos casos es posible cambiar el tamaño de la altura con el atributo rows

textarea.setAttribute('rows',breaks);

Demo

 2
Author: h0mayun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-11 12:48:45

Aquí hay una directiva angularjs para la respuesta de panzi.

 module.directive('autoHeight', function() {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                element = element[0];
                var resize = function(){
                    element.style.height = 'auto';
                    element.style.height = (element.scrollHeight)+'px';
                };
                element.addEventListener('change', resize, false);
                element.addEventListener('cut',    resize, false);
                element.addEventListener('paste',  resize, false);
                element.addEventListener('drop',   resize, false);
                element.addEventListener('keydown',resize, false);

                setTimeout(resize, 100);
            }
        };
    });

HTML:

<textarea ng-model="foo" auto-height></textarea>
 2
Author: chrmcpn,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-28 20:48:46

Como un enfoque diferente, puede usar un <span> que ajusta su tamaño automáticamente. Necesitarás hacerlo editable agregando la propiedad contenteditable="true" y listo:

div {
  width: 200px;
}

span {
  border: 1px solid #000;
  padding: 5px;
}
<div>
  <span contenteditable="true">This text can be edited by the user</span>
</div>

El único problema con este enfoque es que si desea enviar el valor como parte del formulario, tendrá que hacerlo usted mismo en JavaScript. Es relativamente fácil. Por ejemplo, puede agregar un campo oculto y en el evento onsubmit del formulario asignar el valor de span al campo oculto que se enviará automáticamente con el formulario.

 2
Author: Racil Hilan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-24 14:40:25

Algunas de las respuestas aquí no tienen en cuenta el relleno.

Asumiendo que tienes una altura máxima que no quieres repasar, esto funcionó para mí:

    // obviously requires jQuery

    // element is the textarea DOM node

    var $el = $(element);
    // inner height is height + padding
    // outerHeight includes border (and possibly margins too?)
    var padding = $el.innerHeight() - $el.height();
    var originalHeight = $el.height();

    // XXX: Don't leave this hardcoded
    var maxHeight = 300;

    var adjust = function() {
        // reset it to the original height so that scrollHeight makes sense
        $el.height(originalHeight);

        // this is the desired height (adjusted to content size)
        var height = element.scrollHeight - padding;

        // If you don't want a maxHeight, you can ignore this
        height = Math.min(height, maxHeight);

        // Set the height to the new adjusted height
        $el.height(height);
    }

    // The input event only works on modern browsers
    element.addEventListener('input', adjust);
 1
Author: hasen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-01 12:56:05

Un enfoque aún más simple y más limpio es este:

// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
    $(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
    $(this).height( this.scrollHeight );
}).keyup();

/ / y el CSS

textarea.auto-height {
    resize: vertical;
    max-height: 600px; /* set as you need it */
    height: auto;      /* can be set here of in JS */
    overflow-y: auto;
    word-wrap:break-word
}

Todo lo que se necesita es agregar la clase .auto-height a cualquier textarea que desee apuntar.

Probado en FF, Chrome y Safari. Hazme saber si esto no funciona para ti, por cualquier razón. Pero, esta es la forma más limpia y sencilla que he encontrado esto para trabajar. Y funciona muy bien! : D

 1
Author: revive,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-22 06:43:11

Este código funciona para pegar y seleccionar eliminar también.

onKeyPressTextMessage = function(){
			var textArea = event.currentTarget;
    	textArea.style.height = 'auto';
    	textArea.style.height = textArea.scrollHeight + 'px';
};
<textarea onkeyup="onKeyPressTextMessage(event)" name="welcomeContentTmpl" id="welcomeContent" onblur="onblurWelcomeTitle(event)" rows="2" cols="40" maxlength="320"></textarea>

Aquí está el JSFiddle

 1
Author: Kurenai Kunai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-14 08:59:19

Simplemente use <pre> </pre> con algunos estilos como:

    pre {
        font-family: Arial, Helvetica, sans-serif;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-size: 12px;
        line-height: 16px;
    }
 1
Author: Liber,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-30 07:42:01

Esto es lo que hice mientras usaba MVC HTML Helper para TextArea. Tenía bastantes elementos de textarea, así que tuve que distinguirlos usando el Id del modelo.

 @Html.TextAreaFor(m => m.Text, 2, 1, new { id = "text" + Model.Id, onkeyup = "resizeTextBox(" + Model.Id + ");" })

Y en script añadió esto:

   function resizeTextBox(ID) {            
        var text = document.getElementById('text' + ID);
        text.style.height = 'auto';
        text.style.height = text.scrollHeight + 'px';            
    }

Lo he probado en IE10 y Firefox23

 0
Author: gunnerz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-11 13:38:19

Puedes usar este código:

Coffescript:

jQuery.fn.extend autoHeightTextarea: ->
  autoHeightTextarea_ = (element) ->
    jQuery(element).css(
      'height': 'auto'
      'overflow-y': 'hidden').height element.scrollHeight

  @each ->
    autoHeightTextarea_(@).on 'input', ->
      autoHeightTextarea_ @

$('textarea_class_or_id`').autoHeightTextarea()

Javascript

jQuery.fn.extend({
  autoHeightTextarea: function() {
    var autoHeightTextarea_;
    autoHeightTextarea_ = function(element) {
      return jQuery(element).css({
        'height': 'auto',
        'overflow-y': 'hidden'
      }).height(element.scrollHeight);
    };
    return this.each(function() {
      return autoHeightTextarea_(this).on('input', function() {
        return autoHeightTextarea_(this);
      });
    });
  }
});

$('textarea_class_or_id`').autoHeightTextarea();
 0
Author: Darex1991,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-08 15:03:49

Para aquellos que desean que el área de texto sea redimensionada automáticamente tanto en ancho como en alto:

HTML:

<textarea class='textbox'></textarea>
<div>
  <span class='tmp_textbox'></span>
</div>

CSS:

.textbox,
.tmp_textbox {
  font-family: 'Arial';
  font-size: 12px;
  resize: none;
  overflow:hidden;
}

.tmp_textbox {
  display: none;
}

JQuery:

$(function(){
  //alert($('.textbox').css('padding'))
  $('.textbox').on('keyup change', checkSize)
  $('.textbox').trigger('keyup')

  function checkSize(){
    var str = $(this).val().replace(/\r?\n/g, '<br/>');
    $('.tmp_textbox').html( str )
    console.log($(this).val())

    var strArr = str.split('<br/>')
    var row = strArr.length
    $('.textbox').attr('rows', row)
    $('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
  }
})

Codepen:

Http://codepen.io/anon/pen/yNpvJJ

Salud,

 0
Author: Goon Nguyen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-29 04:51:34

La solución de jQuery es establecer la altura del área de texto en 'auto', verificar la altura de desplazamiento y luego adaptar la altura del área de texto a eso, cada vez que cambia un área de texto (JSFiddle):

$('textarea').on( 'input', function(){
    $(this).height( 'auto' ).height( this.scrollHeight );
});

Si está agregando áreas de texto dinámicamente (a través de AJAX o lo que sea), puede agregar esto en su document(documento).listo para asegurarse de que todas las áreas de texto con clase 'autoheight'se mantengan a la misma altura que su contenido:

$(document).on( 'input', 'textarea.autoheight', function() {
    $(this).height( 'auto' ).height( this.scrollHeight );
});

Probado y trabajando en Chrome, Firefox, Opera e IE. También admite cortar y pegar, palabras largas, etc.

 0
Author: patrick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-02 10:25:48

Puede usar este fragmento de código para calcular el número de filas que necesita un área de texto:

textarea.rows = 1;
    if (textarea.scrollHeight > textarea.clientHeight)
      textarea.rows = textarea.scrollHeight / textarea.clientHeight;

Cómpralo en los eventos input y window:resize para obtener el efecto de redimensionamiento automático. Ejemplo en Angular:

Código de plantilla:

<textarea rows="1" reAutoWrap></textarea>

Ajuste automático.directriz.ts

import { Directive, ElementRef, HostListener } from '@angular/core';

@Directive({
  selector: 'textarea[reAutoWrap]',
})
export class AutoWrapDirective {

  private readonly textarea: HTMLTextAreaElement;

  constructor(el: ElementRef) {
    this.textarea = el.nativeElement;
  }

  @HostListener('input') onInput() {
    this.resize();
  }

  @HostListener('window:resize') onChange() {
    this.resize();
  }

  private resize() {
    this.textarea.rows = 1;
    if (this.textarea.scrollHeight > this.textarea.clientHeight)
      this.textarea.rows = this.textarea.scrollHeight / this.textarea.clientHeight;
  }

}
 0
Author: André,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-14 13:22:14

Solución Javascript nativa sin parpadeo en Firefox y más rápido que el método withclientHeight...

1) Agregue div.textarea selector a todos sus selectores que contengan textarea. No olvides añadir box-sizing: border-box;

2) Incluye este script:

function resizeAll()
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      resize(textarea[i]);
}

function resize(textarea)
{
   var div = document.createElement("div");
   div.setAttribute("class","textarea");
   div.innerText=textarea.value+"\r\n";
   div.setAttribute("style","width:"+textarea.offsetWidth+'px;display:block;height:auto;left:0px;top:0px;position:fixed;z-index:-200;visibility:hidden;word-wrap:break-word;overflow:hidden;');
   textarea.form.appendChild(div);
   var h=div.offsetHeight;
   div.parentNode.removeChild(div);
   textarea.style.height=h+'px';
}

function resizeOnInput(e)
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      textarea[i].addEventListener("input",function(e){resize(e.target); return false;},false);
}

window.addEventListener("resize",function(){resizeAll();}, false);
window.addEventListener("load",function(){resizeAll();}, false);
resizeOnInput();

Probado en IE11, Firefox y Chrome.

Esta solución crea div similar a su área de texto, incluido el texto interno y mide la altura.

 0
Author: 18C,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-18 05:49:56

MakeTextAreaResisable que utiliza qQuery

function MakeTextAreaResisable(id) {
    var o = $(id);
    o.css("overflow-y", "hidden");

    function ResizeTextArea() {
        o.height('auto');
        o.height(o[0].scrollHeight);
    }

    o.on('change', function (e) {
        ResizeTextArea();
    });

    o.on('cut paste drop keydown', function (e) {
        window.setTimeout(ResizeTextArea, 0);
    });

    o.focus();
    o.select();
    ResizeTextArea();
}
 0
Author: Igor Krupitsky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-19 18:01:48

Ninguna de las respuestas parece funcionar. Pero este funciona para mí: https://coderwall.com/p/imkqoq/resize-textarea-to-fit-content

$('#content').on( 'change keyup keydown paste cut', 'textarea', function (){
    $(this).height(0).height(this.scrollHeight);
}).find( 'textarea' ).change();
 0
Author: Kim Homann,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-04 11:51:57

He probado script en navegadores comunes, y falló en Chrome y Safari. Es debido a la variable scrollHeight constantemente actualizable.

He aplicado el script Disgustedgoat usando jQuery y he añadido chrome fix

function fitToContent(/* JQuery */text, /* Number */maxHeight) {
    var adjustedHeight = text.height();
    var relative_error = parseInt(text.attr('relative_error'));
    if (!maxHeight || maxHeight > adjustedHeight) {
        adjustedHeight = Math.max(text[0].scrollHeight, adjustedHeight);
        if (maxHeight)
            adjustedHeight = Math.min(maxHeight, adjustedHeight);
        if ((adjustedHeight - relative_error) > text.height()) {
            text.css('height', (adjustedHeight - relative_error) + "px");
            // chrome fix
            if (text[0].scrollHeight != adjustedHeight) {
                var relative = text[0].scrollHeight - adjustedHeight;
                if (relative_error != relative) {
                    text.attr('relative_error', relative + relative_error);
                }
            }
        }
    }
}

function autoResizeText(/* Number */maxHeight) {
    var resize = function() {
        fitToContent($(this), maxHeight);
    };
    $("textarea").attr('relative_error', 0);
    $("textarea").each(resize);
    $("textarea").keyup(resize).keydown(resize);
}
 -1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-09-07 14:01:05