创建具有自动调整大小的文本区域

新手上路,请多包涵

关于这个还有另一个线程,我已经尝试过了。但是有一个问题:如果删除内容, textarea 不会缩小。我找不到任何方法将其缩小到正确的大小 - clientHeight 值返回为 textarea 的完整大小,而不是其内容。

该页面的代码如下:

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 )
    };
}

原文由 DisgruntledGoat 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 741
2 个回答

这对我有用(Firefox 3.64.0 和 Chrome 10/11):

 var observe;
 if (window.attachEvent) {
 observe = function (element, event, handler) {
 element.attachEvent('on'+event, handler);
 };
 }
 else {
 observe = function (element, event, handler) {
 element.addEventListener(event, handler, false);
 };
 }
 function init () {
 var text = document.getElementById('text');
 function resize () {
 text.style.height = 'auto';
 text.style.height = text.scrollHeight+'px';
 }
 /* 0-timeout to get the already changed text */
 function delayedResize () {
 window.setTimeout(resize, 0);
 }
 observe(text, 'change', resize);
 observe(text, 'cut', delayedResize);
 observe(text, 'paste', delayedResize);
 observe(text, 'drop', delayedResize);
 observe(text, 'keydown', delayedResize);

 text.focus();
 text.select();
 resize();
 }
 textarea {
 border: 0 none white;
 overflow: hidden;
 padding: 0;
 outline: none;
 background-color: #D0D0D0;
 }
 <body onload="init();">
 <textarea rows="1" style="height:1em;" id="text"></textarea>
 </body>

如果你想在 jsfiddle 上试试

它从单行开始,仅增长所需的确切数量。单个 textarea 是可以的,但我想写一些我会有很多这样的 textarea 的东西(大约和一个大文本文档中通常有行的一样多)。在那种情况下,它真的很慢。 (在 Firefox 中它非常慢。)所以我真的想要一种使用纯 CSS 的方法。这可以通过 contenteditable 实现,但我希望它是纯文本的。

原文由 panzi 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

以下代码将起作用:

  • 在按键输入上。
  • 使用粘贴文本 (右键单击和 ctrl+v)。
  • 使用剪切文本 (右键单击和 ctrl+x)。
  • 带有预加载的文本。
  • 在所有文本区域 (多行文本框)的 站点范围内。
  • 使用 Firefox (已测试 v31-67)。
  • 使用 Chrome (已测试 v37-74)。
  • 使用 IE (已测试 v9-v11)。
  • 使用 Edge (已测试 v14-v18)。
  • 使用 IOS 浏览器
  • 使用 Android 浏览器
  • 使用 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 = 0;
  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>

在 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 = 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 更新 TEXTAREA

通过 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>

原文由 DreamTeK 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题