Auto expand a textarea using jQuery

2019-01-02 14:39发布

How can I make a textarea automatically expand using jQuery?

I have a textbox for explaining the agenda of the meeting, so I want to expand that textbox when my agenda's text keep growing that textbox area.

标签: jquery
27条回答
春风洒进眼中
2楼-- · 2019-01-02 15:38

This is the solution I ended up using. I wanted an inline solution, and this so far seems to work great:

<textarea onkeyup="$(this).css('height', 'auto').css('height', this.scrollHeight + this.offsetHeight - this.clientHeight);"></textarea>
查看更多
裙下三千臣
3楼-- · 2019-01-02 15:39

I wrote this jquery function that seems to work.

You need to specify min-height in css though, and unless you want to do some coding, it needs to be two digits long. ie 12px;

$.fn.expand_ta = function() {

var val = $(this).val();
val = val.replace(/</g, "&lt;");
val = val.replace(/>/g, "&gt;");
val += "___";

var ta_class = $(this).attr("class");
var ta_width = $(this).width();

var min_height = $(this).css("min-height").substr(0, 2);
min_height = parseInt(min_height);

$("#pixel_height").remove();
$("body").append('<pre class="'+ta_class+'" id="pixel_height" style="position: absolute; white-space: pre-wrap; visibility: hidden; word-wrap: break-word; width: '+ta_width+'px; height: auto;"></pre>');
$("#pixel_height").html(val);

var height = $("#pixel_height").height();
if (val.substr(-6) == "<br />"){
    height = height + min_height;
};
if (height >= min_height) $(this).css("height", height+"px");
else $(this).css("height", min_height+"px");
}
查看更多
回忆,回不去的记忆
4楼-- · 2019-01-02 15:39

@Georgiy Ivankin made a suggestion in a comment, I used it successfully :) -- , but with slight changes:

$('#note').on('keyup',function(e){
    var maxHeight = 200; 
    var f = document.getElementById('note'); 
    if (f.clientHeight < f.scrollHeight && f.scrollHeight < maxHeight ) 
        { f.style.height = f.scrollHeight + 'px'; }
    });      

It stops expanding after it reaches max height of 200px

查看更多
登录 后发表回答