另一个关于这个的话题, ,我已经尝试过。但有一个问题:这 textarea 删除内容后不会缩小。我找不到任何方法将其缩小到正确的尺寸 - clientHeight 值返回为完整大小 textarea, ,而不是其内容。

该页面的代码如下:

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 )
    };
}
有帮助吗?

解决方案

这对我的作品(火狐3.6 / 4.0和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>

如果你想试试的jsfiddle 的 它以一个单一的线只生长所需的确切数额。它是确定一个单一的textarea,但我想写的东西,我会有很多很多很多这样的textareas(大约相当于一个通常具有行大量文本文档)。在这种情况下,它实在是太慢了。 (在Firefox它是出奇的慢。)所以我真的想使用纯CSS的方法。这将有可能contenteditable,但我希望它是纯文本而已。

其他提示

一个完整而又简单的解决方案

更新 07/05/2019 (改善浏览器支持的手机和片)

以下代码会的工作:

  • 关键输入。
  • 用粘贴文本 (右击&ctrl+v)。
  • 与切割文本 (右击&ctrl+x)。
  • 预先加载的文本。
  • 与所有textarea的 (多行文本的) 网站广泛。
  • Firefox (v31-67测试)。
  • (v37-74测试)。
  • (v9-v11测试)。
  • 的边缘 (v14-v18测试)。
  • IOS Safari.
  • Mozilla.
  • 与JavaScript 严格的模式.
  • w3c 验证。
  • 而是精简和效率。

备选案文1 (字)

这个选项需要 jQuery 和已经测试和工作 1.7.2 - 3.3.1

简单的 (添加这码给你的主人脚本文件,并要忘了这件事。)

$('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>

测试jsfiddle


备选案文2 (纯JavaScript)

简单的 (添加这JavaScript到你的主人脚本文件,并要忘了这件事。)

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>

测试jsfiddle


选项3 (jQuery的延伸)

有用的,如果你想要应用还链接到文本域您想要将自动型的。

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

援引用 $('textarea').autoHeight()


更新TEXTAREA通过JAVASCRIPT

当注射内容进一textarea通过JavaScript追加以下代码,以援引的功能选项1。

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

jQuery的溶液 调整的CSS以匹配您的要求

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

的或替代的jQuery 1.7 + ...

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

我已经创建了绝对最低的造型为起点,为您的实验小提琴... 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>
在Firefox 14和铬18.编号24和12是任意的测试

,测试,看看最适合你。

您可以没有风格和脚本标签,但它变得有点凌乱恕我直言(这是老式的HTML + JS,而不是鼓励)。

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

编辑:现代化代码。改变的onkeyup属性对addEventListener。结果 编辑:KEYDOWN作品比KEYUP结果更好 编辑:使用点击之前声明功能 编辑:输入工作优于KEYDOWN(日Thnx @ WASD42&@ MA-Maddin)

的jsfiddle

对我来说,最佳的解决方案(作品和短)是:

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

它像一个魅力而没有与任何糊闪烁(与小鼠也),切割,进入和它缩小到合适的大小。

请看看的jsfiddle

您正在使用的当前clientHeight的较高值和内容scrollHeight属性。当你的小scrollHeight属性通过移除内容,因为clientHeight,以前由style.height设置,拿着它开放计算面积不能变小。您可以改为采取scrollHeight属性的最大值()和您已预定义或textarea.rows计算的最小高度值。

在一般你应该不是真的靠scrollHeight属性的表单控件。除了scrollHeight属性传统上是较少的广泛支持比其他一些IE扩展,HTML / CSS只字未提如何表单控件内部实现,你不能保证scrollHeight属性将是任何有意义的东西。 (传统上,一些浏览器已经使用OS部件的任务,使CSS和他们的内部DOM互动是不可能的。)在对scrollHeight属性/ clientHeight的所有脑干至少嗅试图使生效。

另一种可能的替代办法来避免这个问题,如果它认为它的工作更广泛的可能是使用一个隐藏的div尺寸相同的宽度textarea的,并在相同的字体设置是非常重要的。在KEYUP,复制从文本区域中隐藏的div文本节点文本(记住,以取代“\ n”带有换行符,和逃避“<” /“和”如果正常,你正在使用的innerHTML)。然后简单地测量div的的offsetHeight会给你你需要的高度。

如果您不需要支持IE8可以使用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));
}

现在你只需要添加一些CSS和你做:

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

<强>用法:

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

您可以阅读更多关于它是如何工作的 在我的博客文章

自动尺寸

https://github.com/jackmoore/autosize

独立运行,很受欢迎(截至 2018 年 10 月,GitHub 星数超过 3000 颗),可在 cdnjs)和轻量级(~3.5k)。演示:

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

顺便说一句,如果您使用 ACE 编辑器,请使用 maxLines: Infinity: 自动调整 Ace Cloud 9 编辑器中内容的高度

有没有人考虑CONTENTEDITABLE?没有与滚动瞎搞,一个第二唯一JS我喜欢它,如果你打算节省模糊数据......显然,这是对所有流行的浏览器兼容:的 http://caniuse.com/#feat=contenteditable

只是样式它看起来像一个文本框,并自动调整大小...使其最小高度的首选文字高度,并有它。

什么是酷的这种做法是,你可以保存和标签上的一些浏览器。

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>

我用于多个文本域下面的代码。在铬12,火狐5和IE 9工作正常,甚至与删除,剪切并粘贴在文本域执行的动作。

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

有一种略有不同的方法。

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

我们的想法是将文本从textarea复制到pre,让CSS确保它们具有相同的大小。

的好处是,框架本简单的工具来移动文本而不接触任何事件。也就是说,在AngularJS你就一个ng-model="foo" ng-trim="false"添加到textareang-bind="foo + '\n'"pre。看到拨弄

只要确保pre具有相同的字体大小作为textarea

下列工作的用于切割,粘贴等, 无论这些行动是从鼠标、快捷键,选择一个选项菜单吧...几个答复采取类似的方法,但他们不账户框调整,这就是为什么他们错误地应用风格 overflow: hidden.

我这样做,这也适用 max-heightrows 对最低和最高的高度。

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>

绝对的完整性,你应该打电话的 adjust 功能一些更多情况:

  1. 窗口调整活动,如果宽度 textarea 变化与窗口的调整,或其他活动,改变宽度的textarea
  2. textarea's display 风格属性的变化,例如当它从 none (隐藏), block
  3. 当值的 textarea 被改变的编程方式

注意使用 window.getComputedStyle 或获取 currentStyle 可以在某种程度上在计算价格昂贵,因此可能需要的高速缓存的结果,而不是。

工作IE6,所以我真的希望那就好足够的支持。

作为一个不同的方法,可以使用自动调整其大小<span>。你需要使它变为可编辑通过添加contenteditable="true"财产,你就大功告成了:

div {
  width: 200px;
}

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

这种方法唯一的问题是,如果你要提交的价值形式的一部分,你必须自己在JavaScript这样做。这样做是比较容易的。例如,可以添加一个隐藏字段中和形式的事件onsubmit分配span到隐藏字段将被自动与表单提交的值。

一个位校正。在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;
  });

我知道有jquery.No需要额外的隐藏的div实现这个短和正确的方法,在大多数浏览器工作原理

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

我不知道是否有人提到这一点的方式,但在某些情况下有可能调整高度与行属性

textarea.setAttribute('rows',breaks);

演示

下面是用于潘奇的回答一个angularjs指令。

 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>

可以使用JQuery扩大textarea打字时:

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

这里的某些答案不占填充。

假设你有你不想去在一个maxHeight,这个工作对我来说:

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

一个更简单的,更清洁的方法是这样的:

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

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

所有需要的是将.auto-height类添加到您要针对任何textarea

测试在FF,铬和Safari。让我知道这并不为你工作,以任何理由。但是,这是我发现这个工作最清洁和最简单的方法。而它的伟大工程! :d

此代码适用于粘贴并选择也删除。

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>

下面是的jsfiddle

只要使用<pre> </pre>与像一些方式:

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

谁想要达到相同的在角新版本。

抓斗TEXTAREA elementRef。

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

我还添加了可以来方便另一使用情况下,一些用户读取线程,当用户想增加文本的区域的高度,以一定的高度,然后有它overflow:scroll,上述方法可以被扩展以实现所提到的用例。

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

下面是我在使用MVC HTML辅助的文本区域一样。我有相当多的textarea元素的所以不得不使用模型ID来区分它们。

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

和在脚本中加入这样的:

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

我已经测试了IE10和Firefox23

可以使用以下代码:

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

有关谁想要textarea的被自动调整大小的上宽度和高度:

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

干杯,

jQuery 解决方案是将文本区域的高度设置为“自动”,检查滚动高度,然后在每次文本区域更改时调整文本区域的高度(JSFiddle):

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

如果您动态添加文本区域(通过 AJAX 或其他方式),您可以将其添加到 $(document).ready 中,以确保所有具有“autoheight”类的文本区域与其内容保持相同的高度:

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

已在 Chrome、Firefox、Opera 和 IE 中测试并运行。还支持剪切粘贴、长单词等。

可以使用此片的代码来计算一个textarea需要的行数:

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

计算它inputwindow:resize事件得到自动调整的效果。例如,在角:

模板代码:

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

自动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;
  }

}

本地JavaScript溶液而不在Firefox闪烁和比方法更快withclientHeight ...

1)div.textarea选择添加到含有textarea所有的选择器。不要忘记添加box-sizing: border-box;

2),则包括此脚本:

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

在测试了IE11,Firefox和铬。

该解决方案创建类似于您的textarea格,包括内部文本和测量高度。

使用qQuery MakeTextAreaResisable

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();
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top