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

JavaScript HTML

十三

2020-03-23

关于这个另一个线程,我已经试过。但是有一个问题: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 )
    };
}

第2986篇《创建具有自动调整大小的文本区域》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
蛋蛋猿 2020.03.23

我知道用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>
Gil 2020.03.23

作为一种不同的方法,您可以使用<span>来自动调整其大小。您需要通过添加contenteditable="true"属性使其可编辑,然后完成:

div {
  width: 200px;
}

span {
  border: 1px solid #000;
  padding: 5px;
}
<div>
  <span contenteditable="true">This text can be edited by the user</span>
</div>

这种方法的唯一问题是,如果您想将值作为表单的一部分提交,则必须自己使用JavaScript进行提交。这样做相对容易。例如,您可以添加一个隐藏字段,并且在onsubmit表单的情况下,将的值分配span给该隐藏字段,然后该字段将随表单自动提交。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android