AngularJS directive input width resize by keyup

前端 未结 5 831
余生分开走
余生分开走 2021-01-06 06:36

I created a directive in order to make a input that has width automatically resized when keyup (like Google Contacts). However it seems not to be ok, because the width of ea

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-06 07:02

    So the problem is that you have to measure the text in the input. You can't just guess if you want it to fit right.

    So this one is more complicated than it might sound, but I think I've got a Plunk here for you that will do the trick.

    The basic process:

    1. Create a temporary span.
    2. Apply the same font styling to the span.
    3. Put the value in the span as text.
    4. Measure the span.
    5. Delete the span.

    Code: and Plunk

    app.directive("editInline", function($window){
        return function(scope, element, attr){
          // a method to update the width of an input
          // based on it's value.
          var updateWidth = function () {
              // create a dummy span, we'll use this to measure text.
              var tester = angular.element(''),
              
              // get the computed style of the input
                  elemStyle = $window.document.defaultView
                    .getComputedStyle(element[0], '');
              
              // apply any styling that affects the font to the tester span.
              tester.css({
                'font-family': elemStyle.fontFamily,
                'line-height': elemStyle.lineHeight,
                'font-size': elemStyle.fontSize,
                'font-weight': elemStyle.fontWeight
              });
              
              // update the text of the tester span
              tester.text(element.val());
              
              // put the tester next to the input temporarily.
              element.parent().append(tester);
              
              // measure!
              var r = tester[0].getBoundingClientRect();
              var w = r.width;
              
              // apply the new width!
              element.css('width', w + 'px');
              
              // remove the tester.
              tester.remove();
            };
            
            // initalize the input
            updateWidth();
            
            // do it on keydown so it updates "real time"
            element.bind("keydown", function(){
              
              // set an immediate timeout, so the value in
              // the input has updated by the time this executes.
              $window.setTimeout(updateWidth, 0);
            });
            
        }
    });
    

    EDIT: also, I've changed it to update the input size asynchronously after a keydown event. This will cause it to update more fluidly when you do things like hold a key down.

提交回复
热议问题