简体   繁体   中英

Javascript:Adjust input field width based on text

I am trying to implement auto sized text field based on the solution from this question

<input style="width:20px;" onkeypress="this.style.width = ((this.value.length + 1) * 5) + 'px';"  ng-model="questionButtons[$index].title" type="text" class="edt_spn active" >

it works fine however when the user deletes characters width is not adjusting

 <input style="width:20px;" onkeypress="this.style.width = ((this.value.length + 1) * 5) + 'px';" ng-model="questionButtons[$index].title" type="text" class="edt_spn active" > 

尝试onkeyup事件。

 <input style="width:20px;" onkeyup="this.style.width = ((this.value.length + 1) * 5) + 'px';console.log(this.value.length);" ng-model="questionButtons[$index].title" type="text" class="edt_spn active" > 

I think that the best variant is to use oninput event.

From MDN :

The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.

 <input style="width:20px;" oninput="this.style.width = ((this.value.length + 1) * 5) + 'px';" ng-model="questionButtons[$index].title" type="text" class="edt_spn active" > 

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