Is there anyway to have a textarea “autofit” height based on the content at page load?

前端 未结 13 1738
借酒劲吻你
借酒劲吻你 2020-12-15 17:46

Is there anyway through CSS or Javascript set the height of the textarea based on the content? I have a hardcoded height in my CSS but i wanted it to default so there is no

13条回答
  •  天命终不由人
    2020-12-15 18:12

    Here is a pure javascript solution. No jquery, no plugins, etc.. DEMO

    So how does it work? Suppose you have a default font size/line-height/etc. Well your textarea holds around 11 characters per 100px width. If we can keep this in mind then we can use this function.

    function textareaSetSize(elem, width)
    {
        var length = elem.value.length;
        //about 11 characters per 100 pixels
        var estimatedLines = Math.round(length/(width/100*11));
        //alert('Estimated number of lines: ' + length);
        elem.style.width  = width + 'px';
        elem.rows = estimatedLines;
    }
    

    Then..

        var selector = document.getElementsByClassName('textarea');
        for(var i = 0; i < selector.length; i++)
        {
            selector[i].onkeyup = function(){
                textareaSetSize(this, 400);
            };   
        }
    

    html...

    
    
    
    
    
    

    runnning it...

    textareaSetSize(ta, 500);
    textareaSetSize(ta2, 400);
    textareaSetSize(ta3, 400);
    textareaSetSize(ta4, 400);
    

    This isn't a perfect solution, so if you see an innovation let me know.

提交回复
热议问题