Auto-expanding textarea

后端 未结 5 1928
执念已碎
执念已碎 2020-11-30 00:50

I\'m trying to do a simple auto-expanding textarea. This is my code:

textarea.onkeyup = function () {
  textarea.style.height = textarea.clientHeight + \'px\         


        
5条回答
  •  失恋的感觉
    2020-11-30 01:24

    I've wanted to have the auto-expanding area to be limited by rows number (e.g 5 rows). I've considered using "em" units, for Rob's solution however, this is error-prone and wouldn't take account stuff like padding, etc.

    So this is what I came up with:

    var textarea = document.getElementById("textarea");
    var limitRows = 5;
    var messageLastScrollHeight = textarea.scrollHeight;
    
    textarea.oninput = function() {
        var rows = parseInt(textarea.getAttribute("rows"));
        // If we don't decrease the amount of rows, the scrollHeight would show the scrollHeight for all the rows
        // even if there is no text.
        textarea.setAttribute("rows", "1");
    
        if (rows < limitRows && textarea.scrollHeight > messageLastScrollHeight) {
            rows++;
        } else if (rows > 1 && textarea.scrollHeight < messageLastScrollHeight) {
            rows--;
        }
    
        messageLastScrollHeight = textarea.scrollHeight;
        textarea.setAttribute("rows", rows);
    };
    

    Fiddle: http://jsfiddle.net/cgSj3/

提交回复
热议问题