菜单切换
FACESOHO知行者
心灵
记录
远方
赞赏工具
源代码:
点击运行
保存
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>jquery textarea 内容高度自适应</title> <link href="//cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <!--[if gte IE 9]><!--> <script src="//cdn.staticfile.org/jquery/2.0.3/jquery.min.js"></script> <!--<![endif]--> <!--[if lt IE 9]> <script src="//cdn.staticfile.org/jquery/1.9.1/jquery.min.js"></script> <script src="//cdn.staticfile.org/html5shiv/r29/html5.min.js"></script> <![endif]--> <style type="text/css"> h2{text-align:center;margin:50px auto; } #textarea { width:88%; display:block; margin:0 auto; font-size:14px; height:22%; line-height:24px; padding:2px; } </style> <script> $(document).ready(function($){ $.fn.autoTextarea = function(options) { var defaults={ maxHeight:null, minHeight:$(this).height()},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'; } }); }); }; $(".form-control").autoTextarea({ maxHeight:666,//文本框是否自动撑高,默认:null,不自动撑高;如果自动撑高必须输入数值,该值作为文本框自动撑高的最大高度 }).focus(); }); </script> </head> <body> <h2>文本框根据输入内容自适应高度</h2> <textarea id="textarea" placeholder="回复内容" class="form-control"> 关雎 先秦:佚名 关关雎鸠,在河之洲. 窈窕淑女,君子好逑. 参差荇菜,左右流之. 窈窕淑女,寤寐求之. 求之不得,寤寐思服. 悠哉悠哉,辗转反侧. 参差荇菜,左右采之. 窈窕淑女,琴瑟友之. 参差荇菜,左右芼之. 窈窕淑女,钟鼓乐之. </textarea>
运行结果