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

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

    Tested in chrome

    Pure javascript solution (No plugin, No jquery)

    in action: fiddle

    I created 3 functions:

    • get line height
    • get number of lines
    • set the height of textarea as you type (input event)

        //attach input event
        document.getElementById('ta').addEventListener('input', autoHeight, false);
    
        function autoHeight(e){
            var lh = getLineHeightInPixels(e.target);
            var nol = getNumberOfLines(e.target);
            var ht = lh * nol;
            e.target.style.height = ht + 'px';
        }
    
        function getNumberOfLines(el){
            var text = el.value
            var lines = text.split(/\r|\r\n|\n/);
            return lines.length;
        }
    
        function getLineHeightInPixels(el){
    
            var tempDiv = document.createElement('div');
    
            tempDiv.style.visibility = 'hidden';
    
            tempDiv.style.fontFamily = getComputedStyle(el).getPropertyValue('font-family');
            tempDiv.style.fontSize = getComputedStyle(el).getPropertyValue('font-size');
            tempDiv.style.lineHeight = getComputedStyle(el).getPropertyValue('line-height');
            tempDiv.style.fontVariant = getComputedStyle(el).getPropertyValue('font-variant');
            tempDiv.style.fontStyle = getComputedStyle(el).getPropertyValue('font-style');
    
            tempDiv.innerText = 'abcdefghijklmnopqrstuwxyz';
    
            document.documentElement.appendChild(tempDiv);
    
            var ht = parseInt(getComputedStyle(tempDiv).getPropertyValue('height'))
    
            document.documentElement.removeChild(tempDiv);
            return (ht);
        }
    
        //set height on document load
        document.addEventListener('DOMContentLoaded', function(){document.getElementById('ta').style.height = getLineHeightInPixels(document.getElementById('ta')) + 'px';}, false);

提交回复
热议问题