以下是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);
});
我在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;
}
如果你想实现一个好的效果,只需使用CSS设置最小/最大宽度,并在宽度上使用过渡即可。
您可以在输入元素的data-autosize-input属性中以JSON表示法指定到末尾的空间/距离的值。
当然,您也可以使用jQuery对其进行初始化。
$("selector").autosizeInput();
现有的答案都太复杂了。这里有一个简单的解决方案。
$('#myinput').width($('#myinput').prop('scrollWidth'))
将以上内容添加到输入键按下/弹起/按事件中很容易。 在chrome中测试通过。
简单的东西:
$('#resizeme').keydown(function(){ // listen for keypresses
var contents = $(this).val(); // get value
var charlength = contents.length; // get number of chars
newwidth = charlength*9; // rough guesstimate of width of char
$(this).css({width:newwidth}); // apply new width
});
$(function(){
$("input").keyup(function(){
$(this).stop().animate({
width: $(this).val().length*7
},100)
})
})
所以我做了一个例子,它尝试通过在一个 span 中插入字母并计算宽度来计算宽度。
(function() {
var mDiv = $("<span />").text("M").appendTo("body"),
mSize = mDiv.width();
mDiv.detach();
var letterSize = function(s) {
var sDiv = $("<span />").text("M" + s + "M").appendTo("body"),
sSize = sDiv.width();
sDiv.detach();
return (sSize - (mSize * 2)) * 0.89;
};
$("input[data-resise-me]").each(function() {
var minSize = $(this).width();
var resizeInput = function() {
var calcSize = $.map($(this).val(), letterSize);
var inputSize = 0;
$.each(calcSize, function(i, v) { inputSize += v; });
$(this).width( inputSize < minSize ? minSize : inputSize );
};
$(this).on({ keydown: resizeInput, keyup: resizeInput });
});
} ());
可能有更好的方法来完成这个任务。
正如@ManseUK所提到的,这行代码对我起作用了。 JQuery版本1.8
$('#resizeme').css({width:newwidth});
function resizeInput() {
$('body').append('<div class="new_width">'+$(this).val()+'</div>');
$(this).css('width', $('.new_width').width());
$('.new_width').remove()
}
$('input')
// event handler
.keyup(resizeInput)
// resize on page load
.each(resizeInput);
这个例子已经在Chrome 25和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);
你可以在 js fiddle 上检查这个演示... http://jsfiddle.net/ninadajnikar/bzBdX/9/。
你可以根据自己的喜好更新宽度值