Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
383 views
in Technique[技术] by (71.8m points)

javascript - Dynamically expand height of input type "text" based on number of characters typed into field

Similar to the below JSFiddle (which I bookmarked and do not know from where the original question emerged):

http://jsfiddle.net/mJMpw/6/

<input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 10 }' />

input {
    width: 200px;
    min-width: 200px;
    max-width: 300px;
    transition: width 0.25s;    
}

Is there a way to fix the width of a text field to, for example 200px only, and have the height of the text field grow if a user adds more text than the 200px is able to contain? I would like more rows to be added, if a user needs more room to type... so I need the height, not the width, to resize dynamically.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATED[2]:

As scrollHeight is always equal to height, we have to set height to '1' before scrollHeight, then when we delete characters the <textarea> autofit:

$('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/

UPDATED:

As friends said, <input type="text"/> has no line breaks. My suggest using <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/

ORIGINAL ANSWER:

this is very ugly but you could do it like this:

$('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();
});

You have to specify the same fonts/padding property to .getWidth and you input:

input, .getWidth {
    font-family:arial;
    font-size:12px;
    font-weight:normal;
    letter-spacing:normal;
    padding:3px;
}

Fiddle:

http://jsfiddle.net/9SMRf/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...