search

Home  >  Q&A  >  body text

javascript - How to get the number of automatically wrapped lines in textarea in js?

To enter content in a textarea, the default is one line. When too much content is entered, the line will automatically wrap and the height will increase?

phpcn_u1582phpcn_u15822758 days ago1165

reply all(4)I'll reply

  • 给我你的怀抱

    给我你的怀抱2017-05-16 13:46:17

    1, use shadow

    <p style="height:0; overflow:hidden;">
        <p class="shadow"></p>
    </p>
    <textarea style="overflow:hidden;"></textarea>
    
    <script>
        textarea.addEventListener('input', function(e) {
            shadow.innerHTML = this.value.replace(/\</g, '<').replace(/\>/g, '>');
            this.height = shadow.clientHeight + 'px';
        });
    </script>

    2, use contenteditable attribute

    <p contenteditable="true">这里的高度会随内容自动扩展</p>

    3, if using

    textarea.style.height = textarea.scrollHeight + 'px';

    This form can also adjust the height, but the scroll bar will flash when the line is changed, and the height will only increase but not decrease, which is the worst writing experience.

    reply
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:46:17

    Give the textarea an oninput event

    <textarea id="text"></textarea>
    document.getElementById('text').style.height = document.getElementById('text').scrollHeight + 'px'
    

    Similar to this

    reply
    0
  • PHP中文网

    PHP中文网2017-05-16 13:46:17

    http://stackoverflow.com/ques...

    reply
    0
  • 黄舟

    黄舟2017-05-16 13:46:17

    The total height of the textarea (use jQ’s element.height(), if it is native js, please check the BIF of the manual) / the row height you defined

    reply
    0
  • Cancelreply