还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 )
};
}
自动调整大小
https://github.com/jackmoore/autosize
只是作品,独立,很受欢迎(截至2018年10月,3.0k+ GitHub星),可在cdnjs上使用)和轻量级(~3.5k)。演示:
<textarea id=“autosize” style=“width:200px;”>a
我一
C</textarea>
<script src=“https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js”></script>
<script>autosize(document.querySelectorAll('#autosize'));</script>
顺便说一句,如果你正在使用ACE编辑器,请使用maxLines: Infinity:自动调整ACE Cloud 9编辑器中的内容高度
如果你不需要支持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>
你可以在我的博客文章中阅读更多关于它是如何工作的。
我能够设置TextArea大小在IE9和Chrome与下面的jQuery函数。它绑定到$(document).ready()函数中定义的选择器中的textarea对象。
function autoResize(obj, size) {
obj.keyup(function () {
if ($(this).val().length > size-1) {
$(this).val( function() {
$(this).height(function() {
return this.scrollHeight + 13;
});
alert('The maximum comment length is '+size+' characters.');
return $(this).val().substring(0, size-1);
});
}
$(this).height(function() {
if ($(this).val() == '') {
return 15;
} else {
$(this).height(15);
return ($(this).attr('scrollHeight')-2);
}
});
}).keyup();
}
在我的$(document).ready()函数中,我对本页上的所有textarea调用有以下调用。
$('textarea').each( function() {
autoResize($(this), 250);
});
其中250是文本区域的字符限制。这将增加到文本大小所允许的大小(基于您的字符数和字体大小)。当您从文本区域中删除字符或用户最初粘贴了太多文本时,它还会适当地缩小文本区域。
自动调整大小
https://github.com/jackmoore/autosize
只是作品,独立,很受欢迎(截至2018年10月,3.0k+ GitHub星),可在cdnjs上使用)和轻量级(~3.5k)。演示:
<textarea id=“autosize” style=“width:200px;”>a
我一
C</textarea>
<script src=“https://cdnjs.cloudflare.com/ajax/libs/autosize.js/4.0.2/autosize.min.js”></script>
<script>autosize(document.querySelectorAll('#autosize'));</script>
顺便说一句,如果你正在使用ACE编辑器,请使用maxLines: Infinity:自动调整ACE Cloud 9编辑器中的内容高度