Dynamically Adjust HTML Text Input Width to Content

后端 未结 5 1782
夕颜
夕颜 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:07

    Use onkeypress even

    see this example :http://jsfiddle.net/kevalbhatt18/yug04jau/7/

    
    

    And for placeholder on load use jquery and apply placeholder size in to input

    $('input').css('width',((input.getAttribute('placeholder').length + 1) * 8) + 'px');
    

    Even you can use id instead of input this is just an example so that I used $(input)

    And in css provide min-width

    .form {
        border: 1px solid black;
        text-align: center;
        outline: none;
        min-width:4px;
    }
    


    EDIT:


    If you remove all text from input box then it will take placeholder value using focusout

    Example: http://jsfiddle.net/kevalbhatt18/yug04jau/8/

    $("input").focusout(function(){
    
        if(this.value.length>0){
            this.style.width = ((this.value.length + 1) * 8) + 'px';
        }else{
          this.style.width = ((this.getAttribute('placeholder').length + 1) * 8) + 'px';
        }
    
    });
    

提交回复
热议问题