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

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

    You can use the auto resize plugin using the jQuery UI Autoresize

    Here is the html,

    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script
     src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
    <script src="http://css-tricks.com/examples/TextareaTricks/js/autoresize.jquery.min.js"></script>
    <textarea></textarea>
    

    and here is the jquery,

    $('textarea').autoResize();
    

    see DEMO

    0 讨论(0)
  • 2020-12-15 18:12

    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.

    0 讨论(0)
  • 2020-12-15 18:12

    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");
    
    0 讨论(0)
  • 2020-12-15 18:14

    How about http://www.jacklmoore.com/autosize/ Drop Autosize into any web page and it should Just Work. The source is short and well commented if you are curious to how it works.

    // Example:
    $(document).ready(function(){
        $('textarea').autosize();   
    });
    

    Source: https://github.com/jackmoore/autosize

    Demo: http://www.jacklmoore.com/autosize/

    0 讨论(0)
  • 2020-12-15 18:14

    Hey can go with ExpandingTextArea plugin in which an invisible clone pre element is maintained behind your textarea. Whenever the height of this pre changes, the textarea is updated.

    It is simple just include "expanding.js" and "jQuery" in your page and add class "expanding" to the textarea to which u need to expand.

    <script src='expanding.js'></script>
    <textarea class='expanding'></textarea>
    

    Follow the link for more details and Demo

    Note: It will work on document load for already added texts

    0 讨论(0)
  • 2020-12-15 18:15

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

    0 讨论(0)
提交回复
热议问题