Bra*_*ler 67 javascript scripting jquery
我找到了各种用于自动增长textarea的插件,但没有输入文本字段.有人知道是否存在?
Jam*_*mes 146
这是一个插件,它会做你想要的事情:
编辑:我根据Mathias的评论修复了插件.:)
在这里看一个演示:http://jsfiddle.net/rRHzY
插件:
(function($){
$.fn.autoGrowInput = function(o) {
o = $.extend({
maxWidth: 1000,
minWidth: 0,
comfortZone: 70
}, o);
this.filter('input:text').each(function(){
var minWidth = o.minWidth || $(this).width(),
val = '',
input = $(this),
testSubject = $('<tester/>').css({
position: 'absolute',
top: -9999,
left: -9999,
width: 'auto',
fontSize: input.css('fontSize'),
fontFamily: input.css('fontFamily'),
fontWeight: input.css('fontWeight'),
letterSpacing: input.css('letterSpacing'),
whiteSpace: 'nowrap'
}),
check = function() {
if (val === (val = input.val())) {return;}
// Enter new content into testSubject
var escaped = val.replace(/&/g, '&').replace(/\s/g,' ').replace(/</g, '<').replace(/>/g, '>');
testSubject.html(escaped);
// Calculate new width + whether to change
var testerWidth = testSubject.width(),
newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
currentWidth = input.width(),
isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
|| (newWidth > minWidth && newWidth < o.maxWidth);
// Animate width
if (isValidWidthChange) {
input.width(newWidth);
}
};
testSubject.insertAfter(input);
$(this).bind('keyup keydown blur update', check);
});
return this;
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
我在GitHub上有一个jQuery插件:https://github.com/MartinF/jQuery.Autosize.Input
它使用与James回答相同的方法,但有一些在评论中提到的更改.
你可以在这里看到一个实例:http://jsfiddle.net/mJMpw/6/
例:
<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)
小智 7
好的插件,谢谢!我改变了两件似乎在我的项目中工作得更好的东西.
希望这可以帮助.
归档时间: |
|
查看次数: |
34037 次 |
最近记录: |