我如何自动调整html5 textarea元素的大小/使其适合初始内容?

问题描述 投票:2回答:1

目标:

[我正在寻找一种在JavaScript / jQuery中调整文本区域大小的方法,以使其最初显示其所有文本内容,隐藏垂直滚动条并显示调整大小的句柄。

下面的代码首先显示具有某些内容的文本区域,但不足以显示垂直滚动条。可以,除非我希望文本区域看起来像这样,无论它包含多少文本,即不显示垂直滚动条。

[单击按钮时,会添加更多文本,并显示垂直滚动条,这是我最初在内容过多时要避免的-文本区域应扩展以适合它,我尝试这样做接下来的两个按钮单击。

再次单击该按钮会使文本区域变宽,因此当前行都不会换行。

现在再次单击该按钮会使文本区域变高,因此垂直滚动条不再显示。

但是,文本区域增长太多,在文本的最后一行和文本区域的底行之间显示了一个间隙。不是我想要的。

如果textarea的scrollHeight代表textarea内容的整个高度,并且底部没有空行,为什么会有间隙?

const text = 'This is a line of text';

var   $textarea = $( '#example' );
var   i         = 0;

$textarea.val( $textarea.val() + text );
for( var l = i + 5 ; i < l; ++i )
  $textarea.val( $textarea.val() + "\r\n" + text + '(' + i + ')' );

function doIt( This ) {
  if( This.innerText !== 'Click Me Again' ) {

    for( var l = i + 5 ; i < l; ++i )
      $textarea.val( $textarea.val() + "\r\n" + text + '(' + i + ')' );

    if( This.innerText === 'Click Me' ) {

      This.innerText = 'Click Me Again';
      $( 'p' ).text( 'to make the textarea\s width wider.' );

    }
    else {

      $textarea.css( 'height', $textarea[ 0 ].scrollHeight + 'px' );
      $( 'p' ).html( '<b>Why is there space below the last line of text?</b>' );

    }

  }
  else {

    This.innerText = 'Click Me Some More';
    $textarea.css( 'width', ( $textarea.width() + 36 ) + 'px' );
    $( 'p' ).text( 'to make the textarea\'s height taller and add more text.' );

  }
}
#example { width: 185px; height: 100px; overflow: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>jQuery getScrollBarWidth example</title>
  </head>
  <body>
    <h1>Snippet Example</h1>
    <button onclick="doIt( this );">Click Me</button><br />
    <p>to add more text to the textarea.</p>
    <textarea id="example"></textarea>
  </body>
</html>

谢谢。

javascript jquery html css autoresize
1个回答
0
投票

只需在设置scrollheight之前将高度设置为自动,您就可以了

$textarea.css( 'height', 'auto' );
$textarea.css( 'height', $textarea[ 0 ].scrollHeight + 'px' );
© www.soinside.com 2019 - 2024. All rights reserved.