Dynamically Adjust HTML Text Input Width to Content

后端 未结 5 1786
夕颜
夕颜 2020-12-10 12:38

I can\'t quite find a clear answer on this, and excuse me if there is one I\'ve missed.

I want my text input widths to automatically adjust to the size of the conten

5条回答
  •  北海茫月
    2020-12-10 13:08

    Kevin F is right, there is no native way to do it.

    Here is a one way to do it if you really want it to happen.

    In the code, there is an invisible span where the text is placed. Then we retrieve the width of the span.

    https://jsfiddle.net/r02ma1n0/1/

    var testdiv = $("#testdiv");
    $("input").keydown( function(){
        var ME = $(this);
        //Manual Way
        //var px = 6.5;
        //var txtlength = ME.val().length;
        //$(this).css({width: txtlength * px });
    
       testdiv.html( ME.val() + "--");
       var txtlength = testdiv.width();
       ME.css({width: txtlength  }); 
    });
    

提交回复
热议问题