还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- clientHeight值返回为文本区域的完整大小,而不是它的内容。

该页面的代码如下:

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

当前回答

本地Javascript解决方案没有闪烁在Firefox和更快的方法与clientheight…

1)将div.textarea selector添加到所有包含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和Chrome上测试。

这个解决方案创建div类似于您的文本区域,包括内部文本和测量高度。

其他回答

$('textarea').bind('keyup change', function() {
    var $this = $(this), $offset = this.offsetHeight;
    $offset > $this.height() && $offset < 300 ?
        $this.css('height ', $offset)
            .attr('rows', $this.val().split('\n').length)
            .css({'height' : $this.attr('scrollHeight'),'overflow' : 'hidden'}) :
        $this.css('overflow','auto');
});

我能够设置TextArea大小在IE9和Chrome与下面的jQuery函数。它绑定到$(document).ready()函数中定义的选择器中的textarea对象。

function autoResize(obj, size) {
    obj.keyup(function () {
        if ($(this).val().length > size-1) {
            $(this).val( function() {
                $(this).height(function() {
                    return this.scrollHeight + 13;
                });
                alert('The maximum comment length is '+size+' characters.');
                return $(this).val().substring(0, size-1);
            });
        }
        $(this).height(function() {
            if  ($(this).val() == '') {
                return 15;
            } else {
                $(this).height(15);
                return ($(this).attr('scrollHeight')-2);
            }
        });
    }).keyup();
}

在我的$(document).ready()函数中,我对本页上的所有textarea调用有以下调用。

$('textarea').each( function() {
        autoResize($(this), 250);
});

其中250是文本区域的字符限制。这将增加到文本大小所允许的大小(基于您的字符数和字体大小)。当您从文本区域中删除字符或用户最初粘贴了太多文本时,它还会适当地缩小文本区域。

找到了从这里出发的一班班轮;

<textarea name="text" oninput="this.style.height = ''; this.style.height = this.scrollHeight +'px'"></textarea>

作为一种不同的方法,您可以使用<span>来自动调整它的大小。你需要通过添加contentteditable ="true"属性使其可编辑,这样就完成了:

div { 宽度:200 px; } 跨度{ 边框:1px实心#000; 填充:5 px; } < div > <span contenteditable="true">此文本可以由用户编辑</span> < / div >

这种方法的唯一问题是,如果希望将值作为表单的一部分提交,就必须自己用JavaScript完成。这样做相对容易。例如,您可以添加一个隐藏字段,并在表单的onsubmit事件中将span的值赋给隐藏字段,然后该隐藏字段将自动与表单一起提交。

我不知道是否有人提到这种方式,但在某些情况下,可以用rows属性调整高度

textarea.setAttribute('rows',breaks);

Demo