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 01:47

A nice solution

JSFiddle

HTML

<div id="container">
    <textarea >
    1
    12
    123
    1234
    12345
    123456
    1234567
    </textarea>
</div>

CSS

div#container textarea {
    overflow-y: hidden; /* prevents scroll bar flash */
    padding-top: 1.1em; /* prevents text jump on Enter keypress */
}

JQuery

// auto adjust the height of
$('#container').on( 'keyup', 'textarea', function (e){
    $(this).css('height', 'auto' );
    $(this).height( this.scrollHeight );
});
$('#container').find( 'textarea' ).keyup();
查看更多
再贱就再见
3楼-- · 2020-02-10 01:48

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);
<textarea id="ta"></textarea>

查看更多
混吃等死
4楼-- · 2020-02-10 01:48

I couldn't use scrollHeightas it return 0 on page load (maybe because my textarea is hidden on load). Probably not nest practice (I am a newby in js) but the only option that worked was to count the number of lines in textarea and get length of the longer line in it. Then set the width and height accordingly.

var elements = document.getElementsByTagName("textarea")
for (var i = 0; i < elements.length; i++) {
    var atagelement = elements[i];
    console.log(atagelement.value);

    var textareasplit =atagelement.value.split(/\r|\r\n|\n/);
    var textareaheight =  textareasplit.length *17  // change 17 according to your needs

    var maxline=0
    for  (var j = 0; j < textareasplit.length; j++){
    var line = textareasplit[j];
    var linelenght= line.length;
        if (maxline < linelenght){
            maxline= linelenght;
        };
    };
    var textareawidth= maxline*10  // change 10 according to your needs
    atagelement.setAttribute('style', "width:" + textareawidth+"px ; height:"+textareaheight+"px");

}

If needed, you can also set max-width (or max-height) like this

    var maxwidth= window.innerWidth *0.8
    console.log(maxwidth)
    atagelement.setAttribute('style', "width:" + textareawidth+"px ; height:"+textareaheight+"px ; max-width:" + maxwidth+ "px");
查看更多
兄弟一词,经得起流年.
5楼-- · 2020-02-10 01:50

I don't know why, but it seems my search engine brought me another solution (a "How-To" Tutorial):

http://www.sitepoint.com/build-auto-expanding-textarea-3/

EDIT:

here is the code..

/**
 * TextAreaExpander plugin for jQuery
 * v1.0
 * Expands or contracts a textarea height depending on the
 * quatity of content entered by the user in the box.
 *
 * By Craig Buckler, Optimalworks.net
 *
 * As featured on SitePoint.com:
 * http://www.sitepoint.com/blogs/2009/07/29/build-auto-expanding-textarea-1/
 *
 * Please use as you wish at your own risk.
 */

/**
 * Usage:
 *
 * From JavaScript, use:
 *     $(<node>).TextAreaExpander(<minHeight>, <maxHeight>);
 *     where:
 *       <node> is the DOM node selector, e.g. "textarea"
 *       <minHeight> is the minimum textarea height in pixels (optional)
 *       <maxHeight> is the maximum textarea height in pixels (optional)
 *
 * Alternatively, in you HTML:
 *     Assign a class of "expand" to any <textarea> tag.
 *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand"></textarea>
 *
 *     Or assign a class of "expandMIN-MAX" to set the <textarea> minimum and maximum height.
 *     e.g. <textarea name="textarea1" rows="3" cols="40" class="expand50-200"></textarea>
 *     The textarea will use an appropriate height between 50 and 200 pixels.
 */

(function($) {

    // jQuery plugin definition
    $.fn.TextAreaExpander = function(minHeight, maxHeight) {

        var hCheck = !($.browser.msie || $.browser.opera);

        // resize a textarea
        function ResizeTextarea(e) {

            // event or initialize element?
            e = e.target || e;

            // find content length and box width
            var vlen = e.value.length, ewidth = e.offsetWidth;
            if (vlen != e.valLength || ewidth != e.boxWidth) {

                if (hCheck && (vlen < e.valLength || ewidth != e.boxWidth)) e.style.height = "0px";
                var h = Math.max(e.expandMin, Math.min(e.scrollHeight, e.expandMax));

                e.style.overflow = (e.scrollHeight > h ? "auto" : "hidden");
                e.style.height = h + "px";

                e.valLength = vlen;
                e.boxWidth = ewidth;
            }

            return true;
        };

        // initialize
        this.each(function() {

            // is a textarea?
            if (this.nodeName.toLowerCase() != "textarea") return;

            // set height restrictions
            var p = this.className.match(/expand(\d+)\-*(\d+)*/i);
            this.expandMin = minHeight || (p ? parseInt('0'+p[1], 10) : 0);
            this.expandMax = maxHeight || (p ? parseInt('0'+p[2], 10) : 99999);

            // initial resize
            ResizeTextarea(this);

            // zero vertical padding and add events
            if (!this.Initialized) {
                this.Initialized = true;
                $(this).css("padding-top", 0).css("padding-bottom", 0);
                $(this).bind("keyup", ResizeTextarea).bind("focus", ResizeTextarea);
            }
        });

        return this;
    };

})(jQuery);


// initialize all expanding textareas
jQuery(document).ready(function() {
    jQuery("textarea[class*=expand]").TextAreaExpander();
});

I left the comments in the code since it is not my work ;)

查看更多
疯言疯语
6楼-- · 2020-02-10 01:52

If you dont mind a scollbar inside the text area you can use

$(document).ready(function(){
    tx = $('#textarea')
    tx.height(tx.prop('scrollHeight'));

})

and here is a Fiddle

another Fiddle this has min and max-width set.

but with plug-ins like auto-size

the height of the text box increases with input.

or you can try this plug-in

查看更多
家丑人穷心不美
7楼-- · 2020-02-10 01:52

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';
    }
});
查看更多
登录 后发表回答