jQuery - resizing form input based on value's

2019-01-15 12:59发布

Is it possible to get input's value width and resize the input dynamically so the value will fit?

Here's an example:

http://jsfiddle.net/bzBdX/2/

10条回答
Rolldiameter
2楼-- · 2019-01-15 13:35

I have a jQuery plugin on GitHub: https://github.com/MartinF/jQuery.Autosize.Input

It mirrors the value of the input so it can calculate the actual length instead of guessing or other approaches mentioned.

You can see an live example here: http://jsfiddle.net/jw9oqz0e/

Example:

<input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 40 }' />

input[type="data-autosize-input"] {
  width: 90px;
  min-width: 90px;
  max-width: 300px;
  transition: width 0.25s;    
}

You just use css to set min/max-width and use a transition on the width if you want a nice effect.

You can specify the space / distance to the end as the value in json notation for the data-autosize-input attribute on the input element.

Of course you can also just initialize it using jQuery

$("selector").autosizeInput();
查看更多
欢心
3楼-- · 2019-01-15 13:48

As mentioned by @ManseUK. This line worked for me. JQuery version 1.8

$('#resizeme').css({width:newwidth});

查看更多
Deceive 欺骗
4楼-- · 2019-01-15 13:49

Current answers were waay to complicated. Heres a quick one

$('#myinput').width($('#myinput').prop('scrollWidth'))

Adding the above to input keydown/up/press events is trivial. Tested in chrome

查看更多
手持菜刀,她持情操
5楼-- · 2019-01-15 13:51

this example as been tested on Chrome 25 and Firefox 19. (http://jsfiddle.net/9ezyz/)

function input_update_size()
{
    var value = $(this).val();
    var size  = 12;

    // Looking for font-size into the input
    if (this.currentStyle)
        size = this.currentStyle['font-size'];
    else if (window.getComputedStyle)
        size =  document.defaultView.getComputedStyle(this,null).getPropertyValue('font-size');
    $(this).stop().animate({width:(parseInt(size)/2+1)*value.length},500);
    //$(this).width((parseInt(size)/2+1)*value.length);
}

$('input')
    .each(input_update_size)
    .keyup(input_update_size);
查看更多
登录 后发表回答