關於網頁中文本域高度自動適應問題,參考微信回復
阿新 • • 發佈:2017-09-04
urn 技術 技術分享 idt img col 如果 高度自動適應 xtend
最近手頭有個項目中,有個界面想要做出類似於微信中的回復框,輸入框的高度可以隨文本的輸入,換行等自動適應,先放一個微信中的示例
以此為參考,
廢話不多說,上代碼
1 (function($) { 2 $.fn.autoTextarea = function(options) { 3 var defaults = { 4 maxHeight : null,// 文本框是否自動撐高,默認:null,不自動撐高;如果自動撐高必須輸入數值,該值作為文本框自動撐高的最大高度 5 minHeight : $(this).height()6 // 默認最小高度,也就是文本框最初的高度,當內容高度小於這個高度的時候,文本以這個高度顯示 7 }; 8 var opts = $.extend({}, defaults, options); 9 return $(this).each(function() { 10 $(this).bind("paste cut keydown keyup focus blur", function() { 11 var height, style = this.style; 12this.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);
引用示例
1 $("textarea").autoTextarea({ 2 maxHeight:180//文本框是否自動撐高,默認:null,不自動撐高;如果自動撐高必須輸入數值,該值作為文本框自動撐高的最大高度 3 });
效果圖如下
有用到的朋友可以參考下!
關於網頁中文本域高度自動適應問題,參考微信回復