简体   繁体   中英

How to automatically increase the width of a textarea while text is typed?

I am trying to build a textarea whose width will dynamically increase while inserting text.

I have found many scripts that would dynamically resize a textarea by changing it's height but nothing that meets my needs.

So do you know anything that could help ?

this may help..

<textarea id="tarea" onkeypress="change()" style="width:200;"> </textarea>


<script type="text/javascript"> 
function change() {
    var a = document.getElementById('tarea');
    var len = a.value.length;
    a.style.width = 200 + len;
    alert(a.style.width);
}
</script>

have a good day..

Give the textarea an ID. If the font inside the textarea is monospace is simple. If not is a bit complicated (create a distribution function of the width of a character, get an average use it forward).

On a onkeyup or onkeypressed event use something like

if (document.getElementById('yourid').value.lenght>defaultValue)
{
    defaultValue = defaultValue+charWidth;
    document.getElementById('yourid').width = (defaultValue+charWidth)+'px';       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM