还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 )
    };
}

当前回答

我在常见的浏览器中测试了脚本,在Chrome和Safari中失败了。这是因为不断更新的scrollHeight变量。

我已经使用jQuery应用了wrettledgoat脚本,并添加了chrome修复

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

其他回答

以下是我在使用MVC HTML Helper for TextArea时所做的。我有相当多的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上进行了测试

这是一个jQuery版本的Moussawi7的答案。

$(函数(){ $ (" textarea.auto-grow”)。On ("input", function() { Var元素= $(this)[0]; Element.style.height = "5px"; element.style.height = (element.scrollHeight) + "px"; }); }) textarea { 调整:没有; 溢出:汽车; 宽度:100%; 最小高度:50 px; max-height: 150 px; } < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < textarea类= " auto-grow " > < / >文本区域

这段代码也适用于粘贴和选择删除。

onKeyPressTextMessage = function(){ var textArea =event.currentTarget; 文本区域.样式.高度 = '自动'; 文本区域.样式.高度 = 文本区域.滚动高度 + 'px'; }; <textation onkeyup=“onKeyPressTextMessage(event)” name=“welcomeContentTmpl” id=“welcomeContent” onblur=“onblurWelcomeTitle(event)” rows=“2” cols=“40” maxlength=“320”></textarea>

这是JSFiddle

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/

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

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

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