更新[2]:
As scrollHeight
总是等于height
,我们必须设置height to '1'在scrollHeight之前,那么当我们删除字符时<textarea>
自动调整:
$('textarea').on('keydown', function(e){
if(e.which == 13) {e.preventDefault();}
}).on('input', function(){
$(this).height(1);
var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
$(this).height(totalHeight);
});
Fiddle:
http://jsfiddle.net/mJMpw/551/ http://jsfiddle.net/mJMpw/551/
UPDATED:
正如朋友所说,<input type="text"/>
没有换行符。我的建议使用<textarea>
is:
$('textarea').on({input: function(){
var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
$(this).css({'height':totalHeight});
}
});
Fiddle:
http://jsfiddle.net/mJMpw/548/ http://jsfiddle.net/mJMpw/548/
原答案:
这很丑陋,但你可以这样做:
$('input[type="text"]').on('keyup',function(){
var text = $(this).val();
var getWidth = $('<span class="getWidth" style="white-space:nowrap; width:auto;">' + text + '</span>').insertAfter(this);
$(this).css({'width':getWidth.outerWidth()}).next('.getWidth').remove();
});
您必须为 .getWidth 指定相同的字体/填充属性,然后输入:
input, .getWidth {
font-family:arial;
font-size:12px;
font-weight:normal;
letter-spacing:normal;
padding:3px;
}
Fiddle:
http://jsfiddle.net/9SMRf/ http://jsfiddle.net/9SMRf/