还有另一个关于这个的帖子,我试过了。但有一个问题:如果你删除内容,文本区域不会缩小。我找不到任何方法将其缩小到正确的大小- 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 )
};
}
jQuery的解决方案
请根据实际情况调整CSS
css……
div#container textarea {
min-width: 270px;
width: 270px;
height: 22px;
line-height: 24px;
min-height: 22px;
overflow-y: hidden; /* fixes scrollbar flash - kudos to @brettjonesdev */
padding-top: 1.1em; /* fixes text jump on Enter keypress */
}
javascript……
// auto adjust the height of
$('#container').delegate( 'textarea', 'keydown', function (){
$(this).height( 0 );
$(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keydown();
或替代jQuery 1.7+…
// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (){
$(this).height( 0 );
$(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();
我已经创建了一个具有绝对最小样式的小提琴作为您的实验的起点……
http://jsfiddle.net/53eAy/951/
对于那些想要在宽度和高度上自动调整文本区域的人:
HTML:
<textarea class='textbox'></textarea>
<div>
<span class='tmp_textbox'></span>
</div>
CSS:
.textbox,
.tmp_textbox {
font-family: 'Arial';
font-size: 12px;
resize: none;
overflow:hidden;
}
.tmp_textbox {
display: none;
}
jQuery:
$(function(){
//alert($('.textbox').css('padding'))
$('.textbox').on('keyup change', checkSize)
$('.textbox').trigger('keyup')
function checkSize(){
var str = $(this).val().replace(/\r?\n/g, '<br/>');
$('.tmp_textbox').html( str )
console.log($(this).val())
var strArr = str.split('<br/>')
var row = strArr.length
$('.textbox').attr('rows', row)
$('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
}
})
Codepen:
http://codepen.io/anon/pen/yNpvJJ
欢呼,