还有另外一个关于这个问题,我试过了.但是有一个问题: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) 我正在尝试做一个简单的自动扩展textarea.这是我的代码:
textarea.onkeyup = function () {
textarea.style.height = textarea.clientHeight + 'px';
}
Run Code Online (Sandbox Code Playgroud)
但是当你打字时,textarea会无限增长......
我知道有Dojo和jQuery插件,但不想使用它们.我看了他们的实现,并且最初使用scrollHeight但是做了同样的事情.
您可以开始回答并使用textarea来回答您的问题.