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

当前回答

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

更新2022-08-30 (默认增加了单行多文本框的支持)

下面的代码将工作:

按键输入。 粘贴文本(右键单击并ctrl+v)。 剪切文本(右键单击并ctrl+x)。 与预加载文本。 与所有的文本区域(多行文本框的)网站宽。 使用Firefox (v31-109测试)。 Chrome (v37-108测试)。 使用IE (v9-v11测试)。 使用Edge (v14-v108测试)。 IOS Safari。 Android浏览器。 JavaScript严格模式。


选项1(使用jQuery)

此选项需要jQuery,并且已经过测试,适用于1.7.2 - 3.6.3

简单(将jQuery代码添加到主脚本文件中,然后忘记它)。

$("textarea").each(function () { this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;"); }).on("input", function () { this.style.height = 0; this.style.height = (this.scrollHeight) + "px"; }); <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.6.3.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上测试


OPTION 2(纯JavaScript)

简单(将此JavaScript添加到主脚本文件中,然后忘记它)。

const tx = document.getElementsByTagName("textarea"); for (let 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 = 0; 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": 0, "overflow-y": "hidden" })
        .height(element.scrollHeight);
    }
    return this.each(function() {
      autoHeight_(this).on("input", function() {
        autoHeight_(this);
      });
    });
  }
});

使用$("textarea")调用。autoheight ()


通过javascript更新文本区域

当通过JavaScript向文本区域注入内容时,添加以下代码来调用选项1中的函数。

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

预设文本区域高度

要修复文本区域的初始高度,你需要添加另一个条件:

const txHeight = 16; const tx = document.getElementsByTagName("textarea"); for (let i = 0; i < tx.length; i++) { if (tx[i].value == '') { tx[i].setAttribute("style", "height:" + txHeight + "px;overflow-y:hidden;"); } else { tx[i].setAttribute("style", "height:" + (tx[i].scrollHeight) + "px;overflow-y:hidden;"); } tx[i].addEventListener("input", OnInput, false); } function OnInput(e) { this.style.height = 0; 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>

其他回答

对于那些想要在宽度和高度上自动调整文本区域的人:

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

欢呼,

我知道我迟到了,但我遇到的最简单的解决方案是分割你的文本区域内容在新的行字符和更新文本区域元素的行。

<textarea id="my-text-area"></textarea>

<script>
  $(function() {
    const txtArea = $('#my-text-area')
    const val = txtArea.val()
    const rowLength = val.split('\n')
    txtArea.attr('rows', rowLength)
  })
</script>

如果scrollHeight可以信任,那么:

textarea.onkeyup=function() {
  this.style.height='';
  this.rows=this.value.split('\n').length;
  this.style.height=this.scrollHeight+'px';
}

React的一个示例实现:

const { useLayoutEffect, useState, useRef } = React; const TextArea = () => { const ref = useRef(); const [value, setValue] = useState('Some initial text that both wraps and uses\nnew\nlines'); // This only tracks the auto-sized height so we can tell if the user has manually resized const autoHeight = useRef(); useLayoutEffect(() => { if (!ref.current) { return; } if ( autoHeight.current !== undefined && ref.current.style.height !== autoHeight.current ) { // don't auto size if the user has manually changed the height return; } ref.current.style.height = "auto"; ref.current.style.overflow = "hidden"; const next = `${ref.current.scrollHeight}px`; ref.current.style.height = next; autoHeight.current = next; ref.current.style.overflow = "auto"; }, [value, ref, autoHeight]); return ( <textarea ref={ref} style={{ resize: 'vertical', minHeight: '1em', }} value={value} onChange={event => setValue(event.target.value)} /> ); } ReactDOM.render(<TextArea />, document.getElementById('app')) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="app"></div>

一个更简单、更清晰的方法是:

// 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类添加到您想要的目标文本区域。

在FF, Chrome和Safari测试。如果这对你不起作用,请告诉我,不管是什么原因。但是,这是我发现的最简单明了的方法。而且效果非常好!: D