分享一段代码实例,它实现了textarea文本框能够根据内容高度自适应效果。
在默认情况下如果内容超过textarea文本框的高度,那么就会出现滚动条,有时候这有点不够人性化。
如果能够实现高度自适应效果,那就再好不过了。
代码实例如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> jQuery实现textarea框高度自适应代码示例-搞代码gaodaima.com </title> <script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"> </script> <script type="text/javascript"> jQuery.fn.extend({ autoHeight: function() { return this.each(function() { var $this = jQuery(this); if (!$this.attr('_initAdjustHeight')) { $this.attr('_initAdjustHeight', $this.outerHeight()); } _adjustH(this).on('input', function() { _adjustH(this); }); }); function _adjustH(elem) { var $obj = jQuery(elem); return $obj.css({ height: $obj.attr('_initAdjustHeight'), 'overflow-y': 'hidden' }).height(elem.scrollHeight); } } }); $(function() { $('textarea').autoHeight(); }); </script> </head> <body> <textarea id="txt"> 搞代码,学习知识 </textarea> </body> </html>