还有另外一个关于这个问题,我试过了.但是有一个问题: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 ) …Run Code Online (Sandbox Code Playgroud) 我想制作一本教科书,它以一个给定的宽度/高度开始.然后,如果用户输入的空间超过给定的空间量,则文本框会向下扩展.我该怎么做呢?我使用CSS吗?当用户传递允许的行数时,基本文本框只显示滚动条.如何使文本框再扩展5行呢?
<form method="post" action="">
<textarea name="comments" cols="50" rows="5"></textarea><br>
<input type="submit" value="Submit" />
</form>
Run Code Online (Sandbox Code Playgroud)
我如何使用Robert Harvey提到的例子?我之前从未使用过JavaScript