关于这个还有另一个线程,我已经尝试过了。但是有一个问题:如果删除内容, 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 许可协议
这对我有用(Firefox 3.6⁄4.0 和 Chrome 10/11):
如果你想在 jsfiddle 上试试
它从单行开始,仅增长所需的确切数量。单个
textarea
是可以的,但我想写一些我会有很多这样的textarea
的东西(大约和一个大文本文档中通常有行的一样多)。在那种情况下,它真的很慢。 (在 Firefox 中它非常慢。)所以我真的想要一种使用纯 CSS 的方法。这可以通过contenteditable
实现,但我希望它是纯文本的。