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

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

    
    
    
    Some Title
    
    
    
        
    
    
    
    

    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';
        }
    });
    

提交回复
热议问题