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

当前回答

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>

其他回答

这里有一个明确的答案:

退格增加滚动高度的值

它使用现代ES6语法,解决了添加或删除内容时精确调整大小的问题。它解决了滚动高度值不断变化的问题。

<!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和Chromium 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更好 编辑:在使用之前声明函数 编辑:输入工作更好的按键(thnx @WASD42 & @MA-Maddin)

斯菲德尔

我知道用jquery实现这个的一个简短而正确的方法。没有额外的隐藏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>

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>

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

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

欢呼,