还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 12, Firefox 5和IE 9中工作良好,即使在文本区域执行删除,剪切和粘贴操作。

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 textarea { border: 0 none; overflow: hidden; outline: none; background-color: #eee } <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>

其他回答

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/

这适用于我(Firefox 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 它从一行开始,只增加所需的确切数量。对于一个单一的文本区域是可以的,但是我想写一些东西,我将有很多很多这样的文本区域(大约像一个大文本文档中通常有行一样多)。在这种情况下,它真的很慢。(在Firefox中,它慢得离谱。)所以我真的很喜欢使用纯CSS的方法。这将是可能的contentteditable,但我希望它是纯文本。

这是一种基于行的方法,允许您为文本区域设置最大行数,之后文本区域将显示滚动条。除了以rows属性的形式调整它的高度之外,它还会在键入或执行剪切和粘贴之类的操作时自动扩展它的宽度。

如果文本区域没有任何内容,只有一个占位符,它将根据占位符文本调整其宽度和高度。

这个版本的一个缺点是,它将继续无限增加它的宽度基于文本宽度。因此,你需要为文本区域设置一个max-width值。简单的max-width: 100%;也会有效果。这个宽度扩展特性主要基于type="text"的输入字段。你可以在这个答案中了解更多。

const textarea = document.querySelector('textarea'); setTextareaWidthHeight(textarea); textarea.addEventListener('input', setTextareaWidthHeight.bind(this, textarea)); function getInputWidth(element) { const text = element.value || element.placeholder; const elementStyle = window.getComputedStyle(element); const fontProperty = elementStyle.font; const horizontalBorder = parseFloat(elementStyle.borderLeftWidth) + parseFloat(elementStyle.borderRightWidth); const horizontalPadding = parseFloat(elementStyle.paddingLeft) + parseFloat(elementStyle.paddingRight); const canvas = document.createElement('canvas'); const context = canvas.getContext('2d'); context.font = fontProperty; const textWidth = context.measureText(text).width; const totalWidth = horizontalBorder + horizontalPadding + textWidth + "px"; return totalWidth; } function setTextareaWidthHeight(element) { // store minimum and maximum rows attribute value that should be imposed const minRows = 1; const maxRows = 5; // store initial inline overflow property value in a variable for later reverting to original condition const initialInlineOverflowY = element.style.overflowY; // change overflow-y property value to hidden to overcome inconsistent width differences caused by any scrollbar width element.style.overflowY = 'hidden'; const totalWidth = getInputWidth(element); element.style.width = totalWidth; let rows = minRows; element.setAttribute("rows", rows); while (rows <= maxRows && element.scrollHeight !== element.clientHeight) { element.setAttribute("rows", rows); rows++; } // change overflow to its original condition if (initialInlineOverflowY) { element.style.overflowY = initialInlineOverflowY; } else { element.style.removeProperty("overflow-y"); } } textarea { max-width: 100%; } <textarea placeholder="Lorem ipsum dolor sit amet"></textarea>

我发现最好的方法是:

$("textarea.auto-grow").each( function(){
    $(this).keyup(function(){
        $(this).height( $(this)[0].scrollHeight - Number( $(this).css("font-size").replace("px", "") ) );
    });
});

其他方法有一个字体大小的错误。

这就是为什么这是最好的。

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

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