Resize event for textarea?

2019-01-03 03:31发布

The current versions of Firefox and Chrome include a drag handler to resize a <textarea> box. I need to capture the resizing event, I thought it would be easy with jQuery's resize() event, but it doesn't work!

I have also tried the normal onResize event, but the result is the same. You can try it on JSFiddle.

Is there a way to capture it?

8条回答
太酷不给撩
2楼-- · 2019-01-03 03:55

another way to do it is by binding to the mouseup event on the textarea. then you can check if size changed.

查看更多
等我变得足够好
3楼-- · 2019-01-03 03:58

This is an old question, but someone else had the same one in IRC, so I decided to solve it here: http://jsfiddle.net/vol7ron/Z7HDn/

Chrome doesn't capture the resize event and that Chrome doesn't capture the mousedown, so you need to set the init state and then handle changes through mouseup:

jQuery(document).ready(function(){
   var $textareas = jQuery('textarea');

   // store init (default) state   
   $textareas.data('x', $textareas.outerWidth());
   $textareas.data('y', $textareas.outerHeight()); 

   $textareas.mouseup(function(){

      var $this = jQuery(this);

      if (  $this.outerWidth()  != $this.data('x') 
         || $this.outerHeight() != $this.data('y') )
      {
          // Resize Action Here
          alert( $this.outerWidth()  + ' - ' + $this.data('x') + '\n' 
               + $this.outerHeight() + ' - ' + $this.data('y')
               );
      }

      // store new height/width
      $this.data('x', $this.outerWidth());
      $this.data('y', $this.outerHeight()); 
   });

});

HTML

<textarea></textarea>
<textarea></textarea>

Note:

  1. You could attach your own resizable as Hussein has done, but if you want the original one, you can use the above code
  2. As Bryan Downing mentions, this works when you mouseup while your mouse is on top of a textarea; however, there are instances where that might not happen like when a browser is not maximized and you continue to drag beyond the scope of the browser, or use resize:vertical to lock movement.

    For something more advanced you'd need to add other listeners, possibly a queue and interval scanners; or to use mousemove, as I believe jQuery resizable does -- the question then becomes how much do you value performance vs polish?


Update: There's since been a change to Browsers' UI. Now double-clicking the corner may contract the textbox to its default size. So you also may need to capture changes before/after this event as well.

查看更多
登录 后发表回答