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

当前回答

我的实现非常简单,计算输入中的行数(并且最少2行,以显示它是一个textarea):

textarea.rows = Math.max(2, textarea.value.split("\n").length) // # oninput

刺激的完整工作示例:https://jsbin.com/kajosolini/1/edit?html,js,output

(这适用于浏览器的手动调整大小句柄,例如)

其他回答

您正在使用当前clientHeight和内容scrollHeight的较高值。当您通过删除内容使scrollHeight变小时,计算区域不能变小,因为先前根据样式设置的clientHeight。高度,是撑开它。您可以使用scrollHeight的max()和预定义的或从textarea.rows中计算的最小高度值。

In general you probably shouldn't really rely on scrollHeight on form controls. Apart from scrollHeight being traditionally less widely-supported than some of the other IE extensions, HTML/CSS says nothing about how form controls are implemented internally and you aren't guaranteed scrollHeight will be anything meaningful. (Traditionally some browsers have used OS widgets for the task, making CSS and DOM interaction on their internals impossible.) At least sniff for scrollHeight/clientHeight's existance before trying to enable the effect.

另一种可能的替代方法来避免这个问题,如果重要的是,它可以更广泛地工作,可能是使用一个隐藏的div大小相同的文本区域的宽度,并设置在相同的字体。在keyup上,您将文本从文本区域复制到隐藏div中的文本节点(记住用换行符替换'\n',如果使用innerHTML则正确转义'<'/'&')。然后简单地测量div的offsetHeight将给你你需要的高度。

一个使用React的简单方法。

...
const textareaRef = useRef();

const handleChange = (e) => {
  textareaRef.current.style.height = "auto";
  textareaRef.current.style.height = textareaRef.current.scrollHeight + "px";
};

return <textarea ref={textareaRef} onChange={handleChange} />;

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/

我对多个文本区域使用了以下代码。在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>

有人觉得满意吗?没有混乱的滚动,和唯一的JS我喜欢关于它是如果你计划在模糊保存数据…显然,它在所有流行的浏览器上都是兼容的:http://caniuse.com/#feat=contenteditable

只要把它设置成文本框的样式,它就会自动调整大小……将它的最小高度设置为首选文本高度。

这种方法的最酷之处在于,您可以在某些浏览器上保存和标记。

http://jsfiddle.net/gbutiri/v31o8xfo/

var _auto_value = ''; $(document).on('blur', '.autosave', function(e) { var $this = $(this); if ($this.text().trim() == '') { $this.html(''); } // The text is here. Do whatever you want with it. $this.addClass('saving'); if (_auto_value !== $this.html() || $this.hasClass('error')) { // below code is for example only. $.ajax({ url: '/echo/json/?action=xyz_abc', data: 'data=' + $this.html(), type: 'post', datatype: 'json', success: function(d) { console.log(d); $this.removeClass('saving error').addClass('saved'); var k = setTimeout(function() { $this.removeClass('saved error') }, 500); }, error: function() { $this.removeClass('saving').addClass('error'); } }); } else { $this.removeClass('saving'); } }).on('focus mouseup', '.autosave', function() { var $this = $(this); if ($this.text().trim() == '') { $this.html(''); } _auto_value = $this.html(); }).on('keyup', '.autosave', function(e) { var $this = $(this); if ($this.text().trim() == '') { $this.html(''); } }); body { background: #3A3E3F; font-family: Arial; } label { font-size: 11px; color: #ddd; } .autoheight { min-height: 16px; font-size: 16px; margin: 0; padding: 10px; font-family: Arial; line-height: 20px; box-sizing: border-box; -o-box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; overflow: hidden; display: block; resize: none; border: 0; outline: none; min-width: 200px; background: #ddd; max-height: 400px; overflow: auto; } .autoheight:hover { background: #eee; } .autoheight:focus { background: #fff; } .autosave { -webkit-transition: all .2s; -moz-transition: all .2s; transition: all .2s; position: relative; float: none; } .autoheight * { margin: 0; padding: 0; } .autosave.saving { background: #ff9; } .autosave.saved { background: #9f9; } .autosave.error { background: #f99; } .autosave:hover { background: #eee; } .autosave:focus { background: #fff; } [contenteditable=true]:empty:before { content: attr(placeholder); color: #999; position: relative; top: 0px; /* For IE only, do this: position: absolute; top: 10px; */ cursor: text; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label>Your Name</label> <div class="autoheight autosave contenteditable" contenteditable="true" placeholder="Your Name"></div>