【发布时间】:2010-10-02 00:53:58
【问题描述】:
有another thread about this,我试过了。但是有一个问题:如果您删除内容,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 )
};
}
【问题讨论】:
-
您链接的线程的接受答案对我有用。添加换行符会扩展文本区域,删除它们会缩小文本区域。你用的是什么浏览器?
-
我的函数出错了。必须在行尾键入新行。这是更好的解决方案。 james.padolsey.com/javascript/jquery-plugin-autoresize
-
如果你使用 react,我为此创建了一个包:npmjs.com/package/react-fluid-textarea
标签: javascript html resize height textarea