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

当前回答

有人觉得满意吗?没有混乱的滚动,和唯一的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>

其他回答

jQuery的解决方案是设置文本区域的高度为'auto',检查scrollHeight,然后调整文本区域的高度,每次文本区域改变(JSFiddle):

$('textarea').on( 'input', function(){
    $(this).height( 'auto' ).height( this.scrollHeight );
});

如果你在动态添加文本区域(通过AJAX或其他方式),你可以在$(document)中添加这个。准备好确保所有带有类'autoheight'的文本区域保持与它们的内容相同的高度:

$(document).on( 'input', 'textarea.autoheight', function() {
    $(this).height( 'auto' ).height( this.scrollHeight );
});

测试和工作在Chrome, Firefox, Opera和IE。还支持剪切和粘贴,长字等。

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

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

欢呼,

以下是我在使用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上进行了测试

我创建了一个小的(7kb)自定义元素,为您处理所有这些调整大小的逻辑。

它可以在任何地方工作,因为它是作为自定义元素实现的。包括:虚拟dom (React, Elm等),服务器端呈现的东西,如PHP和简单乏味的HTML文件。

除了监听输入事件外,它还有一个计时器,每100毫秒触发一次,以确保在文本内容通过其他方式发生变化的情况下,事情仍在工作。

下面是它的工作原理:

// At the top of one of your Javascript files
import "autoheight-textarea";

或作为脚本标记包含

<script src="//cdn.jsdelivr.net/npm/autoheight-textarea@1.0.1/dist/main.min.js"></script>

然后像这样包装你的textarea元素

HTML文件

<autoheight-textarea>
  <textarea rows="4" placeholder="Type something"></textarea>
<autoheight-textarea>

React.js组件

const MyComponent = () => {
  return (
    <autoheight-textarea>
      <textarea rows={4} placeholder="Type something..." />
    </autoheight-textarea>
  );
}

下面是Codesandbox上的一个基本演示:https://codesandbox.io/s/unruffled-http-2vm4c

你可以在这里获取软件包:https://www.npmjs.com/package/autoheight-textarea

如果你只是想看看调整大小的逻辑,你可以看看这个函数:https://github.com/Ahrengot/autoheight-textarea/blob/master/src/index.ts#L74-L85

本地Javascript解决方案没有闪烁在Firefox和更快的方法与clientheight…

1)将div.textarea selector添加到所有包含textarea的选择器中。不要忘记添加box-sizing: border-box;

2)包括以下脚本:

function resizeAll()
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      resize(textarea[i]);
}

function resize(textarea)
{
   var div = document.createElement("div");
   div.setAttribute("class","textarea");
   div.innerText=textarea.value+"\r\n";
   div.setAttribute("style","width:"+textarea.offsetWidth+'px;display:block;height:auto;left:0px;top:0px;position:fixed;z-index:-200;visibility:hidden;word-wrap:break-word;overflow:hidden;');
   textarea.form.appendChild(div);
   var h=div.offsetHeight;
   div.parentNode.removeChild(div);
   textarea.style.height=h+'px';
}

function resizeOnInput(e)
{
   var textarea=document.querySelectorAll('textarea');
   for(var i=textarea.length-1; i>=0; i--)
      textarea[i].addEventListener("input",function(e){resize(e.target); return false;},false);
}

window.addEventListener("resize",function(){resizeAll();}, false);
window.addEventListener("load",function(){resizeAll();}, false);
resizeOnInput();

在IE11、Firefox和Chrome上测试。

这个解决方案创建div类似于您的文本区域,包括内部文本和测量高度。