Make an entry to fit your text

I have tried different ways to make an input adapt to is text. The closer I get with jQuery is: $("div").attr("size", $("div").val().length );

I think this works with the attribute size, but this does not seem to measure very well the text. It seems that size works well to measure numbers but not text:



So, when I use size with jQuery:

$("#jQ").attr("size", $("#jQ").val().length );

HTML:

Here is the example to play: http://jsfiddle.net/auk7g40m/

Is there a better way to make an input adapt to its text?

Unless you’re using a monotype font where all the characters have the same width, the easiest way to get the width of a string is to append it to an element, and get the width of the element, like this

$("#jQ").css('width', function() {
    var el = $('', {
        text : this.value,
        css  : {left: -9999, position: 'relative'}
    }).appendTo('body');
    var w = el.css('width');
    el.remove();
    return w;
});

Note that setting the height and width of an element doesn’t really do anything unless the element has position and is not static.


FIDDLE

To make the width follow the keys as they are pressed, you’d just wrap that in an event handler


FIDDLE

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 前端开发 » Make an entry to fit your text

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录