还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 )
};
}
如果你不需要支持IE8,你可以使用input事件:
var resizingTextareas = [].slice.call(document.querySelectorAll('textarea[autoresize]'));
resizingTextareas.forEach(function(textarea) {
textarea.addEventListener('input', autoresize, false);
});
function autoresize() {
this.style.height = 'auto';
this.style.height = this.scrollHeight+'px';
this.scrollTop = this.scrollHeight;
window.scrollTo(window.scrollLeft,(this.scrollTop+this.scrollHeight));
}
现在你只需要添加一些CSS,你就完成了:
textarea[autoresize] {
display: block;
overflow: hidden;
resize: none;
}
用法:
<textarea autoresize>Type here and I’ll resize.</textarea>
你可以在我的博客文章中阅读更多关于它是如何工作的。
jQuery的解决方案是设置文本区域的高度为'auto',检查scrollHeight,然后调整文本区域的高度,每次文本区域改变(JSFiddle):
$('textarea').on( 'input', function(){
$(this).height( 'auto' ).height( this.scrollHeight );
});
如果你在动态添加文本区域(通过AJAX或其他方式),你可以在$(document)中添加这个。准备好确保所有带有类'autoheight'的文本区域保持与它们的内容相同的高度:
$(document).on( 'input', 'textarea.autoheight', function() {
$(this).height( 'auto' ).height( this.scrollHeight );
});
测试和工作在Chrome, Firefox, Opera和IE。还支持剪切和粘贴,长字等。
对于那些正在寻找特定角度的答案的人,你可以使用这个选项来设置默认行数。
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>
这是一种基于行的方法,允许您为文本区域设置最大行数,之后文本区域将显示滚动条。除了以rows属性的形式调整它的高度之外,它还会在键入或执行剪切和粘贴之类的操作时自动扩展它的宽度。
如果文本区域没有任何内容,只有一个占位符,它将根据占位符文本调整其宽度和高度。
这个版本的一个缺点是,它将继续无限增加它的宽度基于文本宽度。因此,你需要为文本区域设置一个max-width值。简单的max-width: 100%;也会有效果。这个宽度扩展特性主要基于type="text"的输入字段。你可以在这个答案中了解更多。
const textarea = document.querySelector('textarea');
setTextareaWidthHeight(textarea);
textarea.addEventListener('input', setTextareaWidthHeight.bind(this, textarea));
function getInputWidth(element) {
const text = element.value || element.placeholder;
const elementStyle = window.getComputedStyle(element);
const fontProperty = elementStyle.font;
const horizontalBorder = parseFloat(elementStyle.borderLeftWidth) + parseFloat(elementStyle.borderRightWidth);
const horizontalPadding = parseFloat(elementStyle.paddingLeft) + parseFloat(elementStyle.paddingRight);
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
context.font = fontProperty;
const textWidth = context.measureText(text).width;
const totalWidth = horizontalBorder + horizontalPadding + textWidth + "px";
return totalWidth;
}
function setTextareaWidthHeight(element) {
// store minimum and maximum rows attribute value that should be imposed
const minRows = 1;
const maxRows = 5;
// store initial inline overflow property value in a variable for later reverting to original condition
const initialInlineOverflowY = element.style.overflowY;
// change overflow-y property value to hidden to overcome inconsistent width differences caused by any scrollbar width
element.style.overflowY = 'hidden';
const totalWidth = getInputWidth(element);
element.style.width = totalWidth;
let rows = minRows;
element.setAttribute("rows", rows);
while (rows <= maxRows && element.scrollHeight !== element.clientHeight) {
element.setAttribute("rows", rows);
rows++;
}
// change overflow to its original condition
if (initialInlineOverflowY) {
element.style.overflowY = initialInlineOverflowY;
} else {
element.style.removeProperty("overflow-y");
}
}
textarea {
max-width: 100%;
}
<textarea placeholder="Lorem ipsum dolor sit amet"></textarea>