dynamically increase input type text textbox width according to the characters entering into it

后端 未结 5 1510
名媛妹妹
名媛妹妹 2020-12-06 21:41

I have a textbox where the user can enter any number of characters, But I want its width to be increased dynamically with respect to the number of chara

5条回答
  •  长情又很酷
    2020-12-06 22:14

    A solution similar to @Tejas', but doesn't require the font to be mono-space:

    The trick is to use scrollWidth, which gives us the total string length, even on single-line textboxes without a scrollbar: https://stackoverflow.com/a/9312727/1869660

    NOTE: I couldn't get this to work in IE, where scrollWidth always returned 2 for some reason..

    Some code:

    function expand(textbox) {
        if (!textbox.startW) { textbox.startW = textbox.offsetWidth; }
    
        var style = textbox.style;
    
        //Force complete recalculation of width
        //in case characters are deleted and not added:
        style.width = 0;
    
        var desiredW = textbox.scrollWidth;
        //Optional padding to reduce "jerkyness" when typing:
        desiredW += textbox.offsetHeight;
    
        style.width = Math.max(desiredW, textbox.startW) + 'px';
    }
    
    ...
    
    
    

    JSFiddle example

提交回复
热议问题