Is there anyway to have a textarea “autofit” heigh

2020-02-10 01:03发布

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 vertical scroll bar on page load?

13条回答
走好不送
2楼-- · 2020-02-10 02:07

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...

<button id="reset">Empty</button>
<textarea class="textarea" id="autosize"></textarea>
<textarea class="textarea" id="autosize2"></textarea>
<textarea class="textarea" id="autosize3"></textarea>
<textarea class="textarea" id="autosize4"></textarea>

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.

查看更多
登录 后发表回答