Textarea自適應文字內容調整高度

Textarea自適應文字內容調整高度學習

在Textarea標籤的使用中,相信你們都遇到過,當內容不少的時候,textarea就會產生一個滾動條,從數據展現來看,很不清晰,可是有不能直接把textarea高度設置得很大,一旦寫死,要不是頁面不協調就是內容展現不清晰,那麼咱們想要的是,textarea的高度可以隨着內容 的多少來自動調節;this

下面附上代碼,望相互學習;spa

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

若有幫助,不勝榮幸;blog

相關文章
相關標籤/搜索