How do I make an expanding textbox?

前端 未结 3 1800
情话喂你
情话喂你 2021-02-04 18:50

I want to make a textbook where it starts out as a given width/height. Then if users type more then the given amount of space, the textbox expands downward. How do I go about do

3条回答
  •  灰色年华
    2021-02-04 19:27

    Here is my solution using only vanilla javascript.
    Tested to work in Chrome, Firefox & IE8 and up.

    On load, or whack it in a function:

    var element = document.getElementById('comments');
    var retractsAutomatically = false;
    
    var sizeOfOne = element.clientHeight;
    element.rows = 2;
    var sizeOfExtra = element.clientHeight - sizeOfOne;
    element.rows = 1;
    
    var resize = function() {
        var length = element.scrollHeight;
    
        if (retractsAutomatically) {
            if (element.clientHeight == length)
                return;
        }
        else {
            element.rows = 1;
            length = element.scrollHeight;
        }
    
        element.rows = 1 + (length - sizeOfOne) / sizeOfExtra;
    };
    
    //modern
    if (element.addEventListener)
        element.addEventListener('input', resize, false);
    //IE8
    else {
        element.attachEvent('onpropertychange', resize)
        retractsAutomaticaly = true;
    }
    

    CSS & HTML:

    textarea#comments { overflow:hidden; }
    
     
    

提交回复
热议问题