Heim  >  Fragen und Antworten  >  Hauptteil

javascript - Wie erhalte ich die Anzahl der automatisch umgebrochenen Zeilen im Textbereich in JS?

Um Inhalte in einen Textbereich einzugeben, ist die Standardeinstellung eine Zeile. Wenn zu viel Inhalt eingegeben wird, wird die Zeile automatisch umbrochen und die Höhe erhöht.

phpcn_u1582phpcn_u15822683 Tage vor1110

Antworte allen(4)Ich werde antworten

  • 给我你的怀抱

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

    1, 用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, '&lt;').replace(/\>/g, '&gt;');
            this.height = shadow.clientHeight + 'px';
        });
    </script>

    2, 用 contenteditable 属性

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

    3, 如果用

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

    这种形式也可以调整高度, 但换行的时候会有滚动条一闪而逝, 而且高度只会增加没法减少, 是体验最差的写法.

    Antwort
    0
  • phpcn_u1582

    phpcn_u15822017-05-16 13:46:17

    给textarea一个oninput事件

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

    类似这样的

    Antwort
    0
  • PHP中文网

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

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

    Antwort
    0
  • 黄舟

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

    textarea的总高度(用jQ的element.height(),如果是原生js,请查看手册的BIF)/ 你定义的行高

    Antwort
    0
  • StornierenAntwort