简体   繁体   中英

Growing text box based on width of characters input

I am trying to create a text box that grows every time a letter is added to it by the width of the character. This is what I'm trying. It doesn't work. If you've got a hint, please share!

JavaScript:

function MakeWidth(el) {
        el.style.width = parseFloat(el.value.clientWidth) }

HTML:

<input id="Test" type="text" style="width: 10px;" onkeyup="MakeWidth(this)"/>

Try size & length instead of clientWidth & width

http://jsfiddle.net/eVd9b/5/

function MakeWidth(el) {
    el.size = parseInt(el.value.length);
}

which should be suitable for your needs.

It may be more useful to use the size attribute.

<input id="Test" type="text" size="1" onkeyup="MakeWidth(this)"/>
<script>
function MakeWidth(el) {
        el.size = el.value.length

}
</script>

That's a bit tricky since you don't necessarily know the width of each character. One little trick that comes to mind is that you could try creating a hidden div with the typed character, grab it's width, add it to the textbox width and destroy the hidden div.

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