Textarea自适应文字内容调整高度

Textarea自适应文字内容调整高度

在Textarea标签的使用中,相信大家都遇到过,当内容很多的时候,textarea就会产生一个滚动条,从数据展示来看,很不清晰,但是有不能直接把textarea高度设置得很大,一旦写死,要不是页面不协调就是内容展示不清晰,那么我们想要的是,textarea的高度能够随着内容 的多少来自动调节;

下面附上代码,望相互学习;

 1 //Textarea自适应文字内容调整高度;
 2 (function($){
 3       $.fn.autoTextarea = function(options) {
 4         var defaults={
 5           maxHeight:null,
 6           minHeight:$(this).height()
 7         };
 8         var opts = $.extend({},defaults,options);
 9         return $(this).each(function() {
10           $(this).bind("paste cut keydown keyup focus",function(){
11             var height,style=this.style;
12             this.style.height = opts.minHeight + 'px';
13             if (this.scrollHeight > opts.minHeight) {
14               if (opts.maxHeight && this.scrollHeight > opts.maxHeight) {
15                 height = opts.maxHeight;
16                 style.overflowY = 'scroll';
17               } else {
18                 height = this.scrollHeight;
19                 style.overflowY = 'hidden';
20               }
21               style.height = height + 'px';
22             }
23           });
24         });
25       };
26     })(jQuery);

使用时:

$(function(){
  $("#content").autoTextarea({
    maxHeight:500,
    minHeight:100//文本框是否自动撑高,默认:null,不自动撑高;如果自动撑高必须输入数值,该值作为文本框自动撑高的最大高度
  });
  $("#content").focus();
});

如有帮助,不胜荣幸;

原文地址:https://www.cnblogs.com/cj28-27/p/6372670.html