Pergunta

Houve outro segmento sobre este , que eu tentei. Mas há um problema: o textarea não encolher se você excluir o conteúdo. Não consigo encontrar alguma maneira de reduzi-lo para o tamanho correto -. O valor clientHeight volta como o tamanho total do textarea, não seu conteúdo

O código a partir dessa página está abaixo:

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 )
    };
}
Foi útil?

Solução

Isso funciona para mim (Firefox 3.6 / 4.0 e 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>

Se você quiser experimentá-lo em jsFiddle Ela começa com uma única linha e cresce apenas a quantidade exata necessária. É ok para uma única textarea, mas eu queria escrever algo onde eu teria muitas muitas muitas dessas textareas (tanto quanto seria normalmente têm linhas em um grande documento de texto). Nesse caso, é realmente lento. (No Firefox é insanamente lento.) Então, eu realmente gostaria de uma abordagem que utiliza CSS puro. Isso seria possível com contenteditable, mas eu quero que seja texto simples somente.

Outras dicas

A COMPLETE mas simples SOLUÇÃO

Atualização 2019/07/05 (suporte ao navegador aprimorado para celulares e tablets)

O código a seguir irá funcionar:

  • Na entrada de chave.
  • Com texto colado (clique direito e ctrl + v).
  • Com texto corte (clique direito e ctrl + x).
  • Com pré-carregado texto.
  • Com tudo do textarea (caixa de texto de várias linhas) todo o site.
  • com Firefox (v31-67 testado).
  • com Chrome (v37-74 testado).
  • com IE (v9-v11 testado).
  • com Borda (v14-v18 testado).
  • com IOS Safari .
  • com Navegador Android .
  • Com JavaScript modo estrito .
  • W3C validado.
  • E é simplificado e eficiente.

OPÇÃO 1 (com jQuery)

Esta opção requer jQuery e foi testado e está trabalhando com 1.7.2 - 3.3.1

simples (Adicione esse código jQuery para seu arquivo de script mestre e esquecê-la.)

$('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://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.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>

teste on jsFiddle


OPÇÃO 2 (Pure JavaScript)

simples (Adicionar este JavaScript para seu arquivo de script mestre e esquecê-la.)

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>

teste on jsFiddle


OPÇÃO 3 (jQuery extensão)

É útil se você deseja aplicar mais de encadeamento para os textareas que você quer ser auto-sized.

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);
      });
    });
  }
});

Invoke com $('textarea').autoHeight()


ACTUALIZAÇÃO TEXTAREA via JavaScript

Ao injetar conteúdo em um textarea via JavaScript acrescentar o seguinte código para invocar a função na opção 1.

$('textarea').trigger('input');

solução jQuery ajustar o css para atender às suas necessidades

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();

OR 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();

Eu criei um violino com o mínimo absoluto denominar como um ponto de partida para as suas experiências ... http://jsfiddle.net/53eAy/951/

<!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>

Testado no Firefox 14 e Cromo 18. Os números 24 e 12 são arbitrários, teste para ver o que melhor lhe convier.

Você poderia fazer sem o estilo e de script tags, mas torna-se um imho pouco confuso (este é estilo antigo HTML + JS e não é incentivada).

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

Editar: código modernizado. Mudou onkeyup atributo para addEventListener.
EDIT: Keydown funciona melhor do que keyup
função declare antes de usar
: Editar Edit: entrada funciona melhor do que keydown (thnx @ WASD42 & @ MA-Maddin)

jsFiddle

A melhor solução (obras e é curto) para mim é:

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

Ele funciona como um encanto sem piscar com pasta (com também mouse), corte, entrando e ele encolhe para o tamanho certo.

Por favor, dê uma olhada jsFiddle .

Você está usando o valor mais elevado do clientHeight atual eo conteúdo scrollHeight. Quando você faz a scrollHeight menor, removendo o conteúdo, a área calculada não pode ficar menor porque o clientHeight, previamente definido pelo style.height, está mantendo-a aberta. Você poderia, em vez dar um max () de scrollHeight e um valor de altura mínima que você tenha pré-definido ou calculado a partir textarea.rows.

Em geral, você provavelmente não deveria realmente confiar scrollHeight em controles de formulário. Além de scrollHeight sendo tradicionalmente menos amplamente suportado do que algumas das outras extensões do IE, HTML / CSS não diz nada sobre como controles de formulário são implementadas internamente e você não está garantido scrollHeight será algo significativo. (Tradicionalmente alguns navegadores têm widgets de sistema operacional utilizado para a tarefa, fazendo CSS e interação DOM em seus internos impossível.) Pelo menos fungada para existência de scrollHeight / clientHeight antes de tentar ativar o efeito.

Outra possível abordagem alternativa para evitar o problema, se é importante que ele funcione de forma mais ampla poderia ser a de usar uma div oculta dimensionada para a mesma largura que o textarea, e colocado na mesma fonte. Em keyup, você copiar o texto da textarea para um nó de texto em div oculta (lembrando-se de substituir '\ n' com uma quebra de linha, e escapar '<' / 'e' corretamente se você estiver usando innerHTML). Em seguida, basta medir offsetHeight do div lhe dará a altura que você precisa.

Se você não precisa apoiar IE8 você pode usar o 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));
}

Agora você só precisa adicionar um pouco de CSS e está feito:

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

Uso:

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

Você pode ler mais sobre como funciona no meu blog .

autosize

https://github.com/jackmoore/autosize

Apenas funciona, autônomo, é populares (3.0k + GitHub estrelas a partir de outubro 2018), disponíveis no cdnjs ) e leve (~ 3.5k). Demonstração:

<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>

BTW, se você estiver usando o editor de ACE, o uso maxLines: Infinity: ajustar automaticamente a altura para conteúdos em Ace Cloud 9 editor

Alguém considerado contenteditable? No andar com rolagem, um nd a única JS I like about it é se você está pensando em salvar os dados no borrão ... e, aparentemente, é compatível com todos os navegadores populares: http://caniuse.com/#feat=contenteditable

estilo Assim que se parecesse com uma caixa de texto, e autosizes ... Faça a sua min-height a altura do texto preferido e têm-no.

fresco do que sobre esta abordagem é que você pode salvar e tags em alguns dos browsers.

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>

Eu usei o seguinte código para múltiplas textareas. funcionando bem no Chrome 12, Firefox 5 e IE 9, mesmo com delete, cortar e colar ações realizadas nas á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>

Há uma abordagem um pouco 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>

A idéia é copiar o texto de textarea no pre e deixe CSS certificar de que eles têm o mesmo tamanho.

A vantagem é que estruturas atuais ferramentas simples para mover o texto ao redor sem tocar quaisquer eventos. Ou seja, em AngularJS você gostaria de acrescentar um ng-model="foo" ng-trim="false" ao textarea e ng-bind="foo + '\n'" ao pre. Veja uma fiddle .

Apenas certifique-se de que pre tem o mesmo tamanho da fonte como o textarea.

As seguintes obras para cortar, colar, etc., independentemente de essas ações são do mouse, um atalho de teclado, selecionando uma opção a partir de uma barra de menu ... várias respostas adoptar uma abordagem semelhante mas não o fazem de conta para a caixa-sizing, que é por isso que eles incorretamente aplicar o overflow: hidden estilo.

Eu faço o seguinte, que também funciona bem com max-height e rows de altura mínima e 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 completar absoluta, você deve chamar a função adjust em mais algumas circunstâncias:

  1. eventos redimensionar a janela, se a largura das mudanças textarea com o redimensionamento da janela, ou outros eventos que mudam a largura da área de texto
  2. Quando atributo de estilo textarea do display muda, por exemplo, quando se vai de none (escondido) para block
  3. Quando o valor do textarea é alterado programaticamente

Note que o uso de window.getComputedStyle ou ficar currentStyle pode ser um pouco computacionalmente caro, então você pode querer armazenar em cache o resultado em seu lugar.

Obras para IE6, então eu realmente espero que isso seja apoio suficiente.

Como uma abordagem diferente, você pode usar um <span> que ajusta seu tamanho automaticamente. Você vai precisar de torná-lo editável, adicionando a propriedade contenteditable="true" e você está feito:

div {
  width: 200px;
}

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

O único problema com esta abordagem é que, se você quiser enviar o valor como parte do formulário, você terá que fazê-lo por si mesmo em JavaScript. Fazer isso é relativamente fácil. Por exemplo, você pode adicionar um campo oculto e em caso onsubmit do formulário de atribuir o valor do span para o campo oculto que será, então, submetido automaticamente com o formulário.

A correções mordeu. Funciona perfeitamente no 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;
  });

Eu sei uma maneira curta e correcta de aplicação do presente com jquery.No adicional div escondida necessário e funciona na maioria dos navegador

<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>

Eu não sei se alguém falar dessa maneira, mas em alguns casos é possível redimensionar a altura com linhas Atributo

textarea.setAttribute('rows',breaks);

Demonstração

Aqui está uma directiva AngularJS pela resposta 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>

Você pode usar JQuery para expandir a textarea enquanto digitando:

$(document).find('textarea').each(function () {
  var offset = this.offsetHeight - this.clientHeight;

  $(this).on('keyup input focus', function () {
    $(this).css('height', 'auto').css('height', this.scrollHeight + offset);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>
<textarea name="note"></textarea>
<div>

Algumas das respostas aqui não conta para preenchimento.

Supondo que você tenha um maxHeight você não quer passar por cima, isso funcionou para mim:

    // 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);

Uma ainda mais simples, a abordagem mais limpa é a seguinte:

// 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();

// eo 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
}

Tudo que é necessário é adicionar a classe .auto-height a qualquer textarea você quiser alvo.

Testado em FF, Chrome e Safari. Deixe-me saber se isso não funcionar para você, por qualquer motivo. Mas, esta é a forma mais limpa e mais simples que eu encontrei este para trabalho. E ele funciona muito bem! : D

Esse código funciona para colar e selecione Excluir também.

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>

Aqui está a jsFiddle

Apenas uso <pre> </pre> com alguns estilos como:

    pre {
        font-family: Arial, Helvetica, sans-serif;
        white-space: pre-wrap;
        word-wrap: break-word;
        font-size: 12px;
        line-height: 16px;
    }

Aqueles que querem conseguir o mesmo em novas versões do Angular.

Grab textArea refElement.

@ViewChild('textArea', { read: ElementRef }) textArea: ElementRef;

public autoShrinkGrow() {
    textArea.style.overflow = 'hidden';
    textArea.style.height = '0px';
    textArea.style.height = textArea.scrollHeight + 'px';
}

<textarea (keyup)="autoGrow()" #textArea></textarea>

Eu também estou adicionando outro caso de uso que podem vir a calhar alguns usuários que lêem o fio, quando o usuário quer aumentar a altura do texto-área a certa altura e depois ter overflow:scroll sobre ele, acima de método pode ser estendido para alcançar o mencionado caso de uso.

  public autoGrowShrinkToCertainHeight() {
    const textArea = this.textArea.nativeElement;
    if (textArea.scrollHeight > 77) {
      textArea.style.overflow = 'auto';
      return;
    }
    else {
      textArea.style.overflow = 'hidden';
      textArea.style.height = '0px';
      textArea.style.height = textArea.scrollHeight + 'px';
    }
  }

Aqui está o que eu fiz enquanto estiver usando MVC Helper HTML para TextArea. Eu tinha muito poucos elementos textarea por isso teve de distingui-los usando Modelo Id.

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

e no roteiro adicionado este:

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

Eu testei-o em IE10 e Firefox23

Você pode usar este código:

Coffeescript:

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();

Para aqueles que querem o textarea para ser auto redimensionada em ambos largura e altura:

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

Cheers,

A solução jQuery é para definir a altura da textarea para 'auto', verifique o scrollHeight e depois adaptar a altura da textarea para que, cada vez que um textarea mudanças ( jsFiddle ):

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

Se você está adicionando dinamicamente textareas (através de AJAX ou qualquer outro), você pode adicionar este no seu $ (document) .ready para garantir que todos os textareas com classe 'autoHeight' são mantidos à mesma altura que seu conteúdo:

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

Testado e trabalhando no Chrome, Firefox, Opera e IE. Também suporta cortar e colar, palavras longas, etc.

Você pode usar este pedaço de código para calcular o número de linhas de textarea necessidades:

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

Compute-lo em eventos input e window:resize para obter efeito de auto-redimensionamento. Exemplo angular em:

código de modelo:

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

auto-wrap.directive.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;
  }

}

Native Javascript solução sem cintilação no Firefox e mais rápido do que o método withclientHeight ...

1) selector Add div.textarea a todos os seus seletores contendo textarea. Não se esqueça de adicionar box-sizing: border-box;

2) Incluir 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();

Testado em IE11, Firefox e Chrome.

Esta solução cria div semelhante ao seu textarea incluindo texto e medidas de altura interna.

MakeTextAreaResisable que usos 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();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top