AngularJS directive input width resize by keyup

前端 未结 5 798
余生分开走
余生分开走 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:24

    You can create a dummy span to store the same string you have in your input textfield.
    On keyup you refresh the span content and get the new length.
    It is better you create a css rule with text style definition for both span and input text, so you are sure they have the same font style.

    Your directive would look like this:

    .html

    blbla

    .js

    app.directive("editInline", function(){
        return function(scope, element, attr){
          var elInput = element.find('input');
          var elDummy = element.find('span');
          var inputText = elInput.val();
          elDummy.html(inputText);
          elInput.bind("keyup", function(){
            var inputText = elInput.val();
            elDummy.html(inputText);
            elInput.css('width', elDummy[0].offsetWidth + 'px');
          });
    
        }
    });  
    

    .css

    input, .dummy {
      font-size: 12px;
      font-family: Arial;
      white-space:pre;
    }
    
    .dummy {
      visibility:hidden; // this would prevent the dummy text to be shown without losing its size
    } 
    

    Here you can see the plunker

提交回复
热议问题