还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 )
};
}
一个更简单、更清晰的方法是:
// adjust height of textarea.auto-height
$(document).on( 'keyup', 'textarea.auto-height', function (e){
$(this).css('height', 'auto' ); // you can have this here or declared in CSS instead
$(this).height( this.scrollHeight );
}).keyup();
//和CSS
textarea.auto-height {
resize: vertical;
max-height: 600px; /* set as you need it */
height: auto; /* can be set here of in JS */
overflow-y: auto;
word-wrap:break-word
}
所有需要做的就是将.auto-height类添加到您想要的目标文本区域。
在FF, Chrome和Safari测试。如果这对你不起作用,请告诉我,不管是什么原因。但是,这是我发现的最简单明了的方法。而且效果非常好!: D
对于那些正在寻找特定角度的答案的人,你可以使用这个选项来设置默认行数。
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>
以下是我在使用MVC HTML Helper for TextArea时所做的。我有相当多的textarea元素,所以必须使用模型Id来区分它们。
@Html.TextAreaFor(m => m.Text, 2, 1, new { id = "text" + Model.Id, onkeyup = "resizeTextBox(" + Model.Id + ");" })
并在脚本中添加了这个:
function resizeTextBox(ID) {
var text = document.getElementById('text' + ID);
text.style.height = 'auto';
text.style.height = text.scrollHeight + 'px';
}
我在IE10和Firefox23上进行了测试