最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Growing text box based on width of characters input - Stack Overflow

programmeradmin0浏览0评论

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)"/>

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)"/>
Share Improve this question asked Nov 13, 2011 at 19:52 Michael SwartsMichael Swarts 3,9218 gold badges36 silver badges46 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

Try size & length instead of clientWidth & width

http://jsfiddle/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 es 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.

发布评论

评论列表(0)

  1. 暂无评论