Mar*_*inF 11
我在GitHub上有一个jQuery插件:https://github.com/MartinF/jQuery.Autosize.Input
它反映了输入的值,因此它可以计算实际长度,而不是猜测或提到的其他方法.
你可以在这里看到一个实例:http://jsfiddle.net/jw9oqz0e/
例:
<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;
}
Run Code Online (Sandbox Code Playgroud)
如果你想要一个很好的效果,你只需使用css设置最小/最大宽度并在宽度上使用过渡.
您可以将结尾的空间/距离指定为输入元素上data-autosize-input属性的json表示法中的值.
当然你也可以使用jQuery初始化它
$("selector").autosizeInput();
Run Code Online (Sandbox Code Playgroud)
Dav*_*rge 10
这是jQuery代码:
$('input').each(function(){
var value = $(this).val();
var size = value.length;
// playing with the size attribute
//$(this).attr('size',size);
// playing css width
size = size*2; // average width of a char
$(this).css('width',size*3);
})?;
Run Code Online (Sandbox Code Playgroud)
目前的答案是复杂的.这是一个快速的
$('#myinput').width($('#myinput').prop('scrollWidth'))
Run Code Online (Sandbox Code Playgroud)
将上述内容添加到输入keydown/up/press事件是微不足道的.镀铬测试