1. 程式人生 > >jquery實現textarea 高度自適應

jquery實現textarea 高度自適應

轉載自:http://www.jb51.net/article/61997.htm

用jquery實現的textarea 高度自適應程式碼。這個動畫效果比較流暢。適合新手學習。非常簡單實用,這裡推薦給小夥伴們。

之前給大家分享過用Javascript控制文字框textarea高度隨內容自適應增長收縮,今天花了點時間換了種實現方法,總結一下

複製程式碼 程式碼如下:
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);
                    });
                });
                /**
                 * 重置高度
                 * @param {Object} elem
                 */
                function _adjustH(elem){
                    var $obj = jQuery(elem);
                    return $obj.css({height: $obj.attr('_initAdjustHeight'), 'overflow-y': 'hidden'})
                            .height( elem.scrollHeight );
                }
            }
        });
        // 使用
        $(function(){
            $('textarea').autoHeight();
        });