Implementing a resizable textarea?

后端 未结 5 2049
深忆病人
深忆病人 2020-12-07 14:44

How does Stackoverflow implement the resizable textarea?

Is that something they rolled themselves or is it a publicly available component that I can easily attach to

5条回答
  •  悲&欢浪女
    2020-12-07 15:23

    Using AngularJS:

    angular.module('app').directive('textarea', function() {
      return {
        restrict: 'E',
        controller: function($scope, $element) {
          $element.css('overflow-y','hidden');
          $element.css('resize','none');
          resetHeight();
          adjustHeight();
    
          function resetHeight() {
            $element.css('height', 0 + 'px');
          }
    
          function adjustHeight() {
            var height = angular.element($element)[0]
              .scrollHeight + 1;
            $element.css('height', height + 'px');
            $element.css('max-height', height + 'px');
          }
    
          function keyPress(event) {
            // this handles backspace and delete
            if (_.contains([8, 46], event.keyCode)) {
              resetHeight();
            }
            adjustHeight();
          }
    
          $element.bind('keyup change blur', keyPress);
    
        }
      };
    });
    

    This will transform all your textareas to grow/shrink. If you want only specific textareas to grow/shrink - change the top part to read like this:

    angular.module('app').directive('expandingTextarea', function() {
      return {
        restrict: 'A',
    

    Hope that helps!

提交回复
热议问题