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

前端 未结 13 1726
借酒劲吻你
借酒劲吻你 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:32

    The only css I use below on the textarea is its width, there is no need to set an initial height. overflow should not be needed either as the scrollHeight that will be used is:

    a measurement of the height of an element's content including content not visible on the screen due to overflow.

    scrollHeight :MDN

    If you want to work with Internet Explorer though, then it is necessary to use overflow: auto as otherwise IE insists on adding a vertical scrollbar (even though there is nothing to scroll).

    Note that the width does not need to be specified either, but it is the property that is most commonly set in relation to this topic.

    This is the JavaScript needed:

    document.addEventListener("DOMContentLoaded", function(event) {
        var ta = document.getElementById('ta');
        ta.style.height = ta.scrollHeight + 'px';
    });
    

    When the DOM has loaded the height of the textarea is set to its scrollHeight.

    Here is a complete page for testing:

    <!DOCTYPE html>
    <html>
    <head>
    <title>Some Title</title>
    <style>
    textarea {
        width: 300px;
        overflow: auto;
    }
    </style>
    </head>
    <body>
        <textarea id="ta">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</textarea>
    <script>
        document.addEventListener("DOMContentLoaded", function(event) {
            var ta = document.getElementById('ta');
            ta.style.height = ta.scrollHeight + 'px';
        });
    </script>
    </body>
    </html>
    

    If required, the code can be applied to all textareas on the page:

    document.addEventListener("DOMContentLoaded", function(event) {
        var tas = document.getElementsByTagName('textarea');
        for (var i=0; i < tas.length; i++) {
            tas[i].style.height = tas[i].scrollHeight + 'px';
        }
    });
    
    0 讨论(0)
提交回复
热议问题