自动设置textarea的高度

时间:2013-04-07 12:20:24

标签: javascript jquery html

我有一个textarea,我希望自动增加高度,但它不起作用,这是我的 jQuery

$('.flat_textarea').delegate( 'textarea', 'keyup', function (){
   $(this).height( 30 );
   if(this.scrollHeight>30) 
 $(this).height(this.scrollHeight);
});

$('.flat_textarea').find( 'textarea' ).keyup();

$('.flat_textarea textarea').on("keyup",function (){
  $(this).height( 30 );
  if(this.scrollHeight>30) 
    $(this).height(this.scrollHeight);
});

HTML:

<form method="POST" class="flat_textarea" >
    <textarea></textarea>
</form>

1 个答案:

答案 0 :(得分:1)

使用on()代替delegate()(不推荐使用delegate()) - 而keypress()代替keyup()。

这是一个有效的jsFiddle

将您的代码更改为以下内容:

$('.flat_textarea').on('keypress', 'textarea', function (){
   $(this).height(30);
   if(this.scrollHeight > 30) 
     $(this).height(this.scrollHeight);
});

$('.flat_textarea').find('textarea').keypress();

$('.flat_textarea textarea').on("keypress", function (){
  $(this).height(30);
  if(this.scrollHeight > 30) 
    $(this).height(this.scrollHeight);
});
相关问题