还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- clientHeight值返回为文本区域的完整大小,而不是它的内容。
该页面的代码如下:
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 )
};
}
对于那些正在寻找特定角度的答案的人,你可以使用这个选项来设置默认行数。
create directive
@Directive({
selector: '[appTextAreaAutoHeight]'
})
export class TextAreaAutoHeightDirective implements AfterViewInit {
private row = 1;
constructor(private el: ElementRef) {
this.row = el.nativeElement.rows;
}
ngAfterViewInit(): void {
const elem = this.el.nativeElement;
elem.style.height = "1px";
elem.style.minHeight = (this.row * elem.scrollHeight) + "px";
}
@HostListener('input', ['$event.target'])
onInput(elem: any) {
elem.style.height = "1px";
elem.style.height = (elem.scrollHeight) + "px";
}
}
使用方法:
<textarea id="title" rows="3" class="col-12 p-1 fs-15 fw-reg
rounded-1" appTextAreaAutoHeight
placeholder="...*******$$$"></textarea>
这是一个angularjs指令,用于panzi的答案。
module.directive('autoHeight', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element = element[0];
var resize = function(){
element.style.height = 'auto';
element.style.height = (element.scrollHeight)+'px';
};
element.addEventListener('change', resize, false);
element.addEventListener('cut', resize, false);
element.addEventListener('paste', resize, false);
element.addEventListener('drop', resize, false);
element.addEventListener('keydown',resize, false);
setTimeout(resize, 100);
}
};
});
HTML:
<textarea ng-model="foo" auto-height></textarea>