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

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

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

    This work for me

    $(function(){
        $('body').on('keydown','textarea', function(event) {
            if ($('textarea')[0].clientHeight < $('textarea')[0].scrollHeight)
            {
                $('textarea').css({'height': $('textarea')[0].scrollHeight+"px"});
            }
            else
            {
                // reset height to default value
                $('textarea').css({'height': ''});
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-15 18:17

    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

    0 讨论(0)
  • 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);
    <textarea id="ta"></textarea>

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

    Without plugins you could do something like

    $(document).ready(function(){
      elem=document.getElementById('#elemid');
      while(elem.clientHeight < elem.scrollHeight) {elem.height(elem.height()+10)}
    });
    

    Resizing the textarea while it does have a scrollbar (so elem.clientHeight < elem.scrollHeight). You can do it quite easily even without JQuery, in plain javascript.

    Didn't test the code, it's just the "concept".

    EDIT: Dumb me, it's much easier, no loops...

    if (elem.clientHeight < elem.scrollHeight) elem.style.height=elem.scrollHeight+"px";
    
    0 讨论(0)
  • 2020-12-15 18:29

    This other question about WhatsApp like input has been incorrectly marked as a duplicate of this current question. As I cannot answer there, I'm answering it here.

    I was trying to create a WhatsApp like input area, with the following features:

    1. The div/textarea should expand upwards when the content exceeds 4em
    2. Max height of the div/textarea should be 6em
    3. The messaging area (above the div/textarea) should reduce i.e. its scrollbar thumbtack size should change.

    Here is my pure CSS solution, if anyone is looking for it (like I was a few minutes ago).

    .arena {
      position: absolute;
      height: 20em;
      width: 12em;
      background-color: #efefef;
      padding: 1em;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }
    .messages {
      padding: 0.2em;
      height: 5em;
      flex: 1 1 0;
      overflow: auto;
    }
    .content {
      background-color: teal;  
      height: 20em;
    }
    .footer {
      position: relative;
      background-color: #cdcdcd;
      padding: 0.2em;
    }
    .editable {
      outline: none;
      max-height: 6em;
      min-height: 4em;
      overflow: auto;
      width: 80%;
      background-color: #fff;
    }
    <div class="arena">
      <div class="messages">
        <div class="content"></div>
      </div>
      <div class="footer">
        <div class="editable" contenteditable="true"></div>
      </div>
    </div>

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