一个完整而简单的解决方案
2020 年 5
月14 日更新(改进了对手机和平板电脑的浏览器支持)
以下代码将起作用:
- 在按键输入上。
 
- 带有粘贴的文本(右键单击和 ctrl+v)。
 
- 带有剪切文本(右键单击和 ctrl+x)。
 
- 带有预加载的文本。
 
- 在所有 textarea (多行文本框)站点范围内。
 
- 使用Firefox  (经过 v31-67 测试)。
 
- 使用Chrome  (经过 v37-74 测试)。
 
- 使用IE  (经过 v9-v11 测试)。
 
- 使用Edge  (经过 v14-v18 测试)。
 
- 与IOS Safari。
 
- 使用安卓浏览器。
 
- 使用 JavaScript严格模式。
 
- 是否经过w3c验证。
 
- 并且精简高效。
 
选项 1 (使用 jQuery)
此选项需要jQuery并且已经过测试并且正在使用1.7.2 - 3.6
简单 (将此 jquery 代码添加到您的主脚本文件并忘记它。)
$("textarea").each(function () {
  this.setAttribute("style", "height:" + (this.scrollHeight) + "px;overflow-y:hidden;");
}).on("input", function () {
  this.style.height = "auto";
  this.style.height = (this.scrollHeight) + "px";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.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>
 
 
Test on jsfiddle
选项 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 = "auto";
  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>
 
 
Test on jsfiddle
选项 3 (jQuery 扩展)
如果您想对要自动调整大小的文本区域应用进一步的链接,则很有用。
jQuery.fn.extend({
  autoHeight: function () {
    function autoHeight_(element) {
      return jQuery(element)
        .css({ "height": "auto", "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");
预设文本区域高度
要修复 textarea 的初始高度,您需要添加一个附加条件:
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 = "auto";
  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>