Jquery implements textarea to adapt the height according to the text content

  • 2020-05-26 07:44:39
  • OfStack

When playing weibo, we may notice that the height of the default text box given to you by both sina weibo and tencent weibo when forwarding and commenting is not very high. This may be because the layout is limited and users usually only broadcast or comment on a short sentence. But when you type more than one line of text, the height of the text box is automatically raised, greatly improving the experience, so that the user can see the entire text. No more dragging the text box's scroll bar.

autoTextarea.js


(function($){
  $.fn.autoTextarea = function(options) {
    var defaults={
      maxHeight:null,
      minHeight:$(this).height()
    };
    var opts = $.extend({},defaults,options);
    return $(this).each(function() {
      $(this).bind("paste cut keydown keyup focus blur",function(){
        var height,style=this.style;
        this.style.height = opts.minHeight + 'px';
        if (this.scrollHeight > opts.minHeight) {
          if (opts.maxHeight && this.scrollHeight > opts.maxHeight) {
            height = opts.maxHeight;
            style.overflowY = 'scroll';
          } else {
            height = this.scrollHeight;
            style.overflowY = 'hidden';
          }
          style.height = height + 'px';
        }
      });
    });
  };
})(jQuery);

demo.js


$(".doctable textarea").autoTextarea({
  maxHeight:400,
  minHeight:100
});

That's all for this article, and I hope it can help you learn jQuery.


Related articles: