javascript - How to get the number of automatically wrapped lines in textarea in js?
phpcn_u1582
phpcn_u1582 2017-05-16 13:44:17
0
4
1149

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_u1582
phpcn_u1582

reply all(4)
给我你的怀抱

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.

phpcn_u1582

Give the textarea an oninput event

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

Similar to this

Ty80

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

黄舟

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!