jQuery - 自动调整大小的文本输入(不是 textarea!)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1288297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - auto size text input (not textarea!)
提问by migajek
How do I auto-resize the input type="text" field with jQuery? I want it to be like 100px wide at the start, then make it auto-widening as user inputs text... is that possible?
如何使用 jQuery 自动调整 input type="text" 字段的大小?我希望它在开始时像 100px 宽,然后让它在用户输入文本时自动加宽......这可能吗?
回答by seize
Here's a plugin that'll do what you're after:
这是一个插件,可以满足您的需求:
The plugin:
插件:
(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);
EDIT:Found on: Is there a jQuery autogrow plugin for text fields?
编辑:发现于:是否有用于文本字段的 jQuery 自动增长插件?
回答by RaYell
I don't think there is a perfect solution to that problem because you cannot detect the actual width of the text entered to the input element. It all depends of the font you are using, zoom settings in browser etc.
我认为该问题没有完美的解决方案,因为您无法检测输入到 input 元素的文本的实际宽度。这完全取决于您使用的字体、浏览器中的缩放设置等。
However if you can choose a font where you can actually calculate the number of pixels that text have (this is the hardest part but I guess you can try to estimate it somehow). You can use this to change the width of your input field.
但是,如果您可以选择一种字体,您可以在其中实际计算文本具有的像素数(这是最难的部分,但我想您可以尝试以某种方式估计它)。您可以使用它来更改输入字段的宽度。
$('input').keyup(function () {
// I'm assuming that 1 letter will expand the input by 10 pixels
var oneLetterWidth = 10;
// I'm also assuming that input will resize when at least five characters
// are typed
var minCharacters = 5;
var len = $(this).val().length;
if (len > minCharacters) {
// increase width
$(this).width(len * oneLetterWidth);
} else {
// restore minimal width;
$(this).width(50);
}
});
回答by thor222
(Edited:using the .text()
method instead of .html()
to get all formatting right.)
(编辑:使用该.text()
方法而不是.html()
使所有格式正确。)
Hello I dont know if you are still looking but i came across this when i was looking for a script to do the same thing. So hope this helps anyone who is trying to do this, or something similar.
你好,我不知道你是否还在寻找,但我在寻找一个脚本来做同样的事情时遇到了这个。所以希望这可以帮助任何试图这样做的人,或类似的事情。
function editing_key_press(e){
if(!e.which)editing_restore(this.parentNode);
var text = $('<span>')
.text($(this).val())
.appendTo(this.parentNode);
var w = text.innerWidth();
text.remove();
$(this).width(w+10);
}
The logic to this code is to put the content onto the page in a span and then gets the width of this content and removes it. The problem i did have was with it was that i had to get it to run on both keydown and keyup for it to work successfully.
这段代码的逻辑是将内容放在一个跨度中的页面上,然后获取此内容的宽度并将其删除。我确实遇到的问题是我必须让它在 keydown 和 keyup 上运行才能成功运行。
Hope this helps, Might not as i have only been doing jquery for a short amount of time.
希望这会有所帮助,可能不会,因为我只在短时间内使用 jquery。
Thanks
谢谢
George
乔治
回答by MartinF
I have a jQuery plugin on GitHub: https://github.com/MartinF/jQuery.Autosize.Input
我在 GitHub 上有一个 jQuery 插件:https: //github.com/MartinF/jQuery.Autosize.Input
It uses the same approach as seize's answer but have some of the changes mentioned in the comments.
它使用与 seize 的答案相同的方法,但在评论中提到了一些变化。
You can see an live example here: http://jsfiddle.net/mJMpw/6/
你可以在这里看到一个活生生的例子:http: //jsfiddle.net/mJMpw/6/
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.
如果你想要一个好的效果,你只需使用 css 来设置最小/最大宽度并在宽度上使用过渡。
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.
您可以为 input 元素上的 data-autosize-input 属性指定到末尾的空间/距离作为 json 表示法中的值。
Of course you can also just initialize it using jQuery
当然你也可以使用jQuery初始化它
$("selector").autosizeInput();
回答by Sarah Vessels
I used seize's answer, but made these changes:
我使用了seize 的答案,但做了以下更改:
Between setting
isValidWidthChange
and// Animate width
:if (!isValidWidthChange && newWidth > minWidth && newWidth > o.maxWidth) { newWidth = o.maxWidth; isValidWidthChange = true; }
This way the input will grow as big as you've allowed it when its contents are too big to fit within the max width.
After
$(this).bind('keyup keydown blur update', check);
:// Auto-size when page first loads check();
在设置
isValidWidthChange
和之间// Animate width
:if (!isValidWidthChange && newWidth > minWidth && newWidth > o.maxWidth) { newWidth = o.maxWidth; isValidWidthChange = true; }
这样,当输入的内容太大而无法容纳在最大宽度内时,输入将增长到您允许的那样大。
之后
$(this).bind('keyup keydown blur update', check);
:// Auto-size when page first loads check();
回答by Dmitry Pashkevich
See this jQuery plugin:
https://github.com/padolsey/jQuery.fn.autoResize
看到这个 jQuery 插件:
https://github.com/padolsey/jQuery.fn.autoResize
I just tested it out with textareas and it works! Supports auto-growing of textareas, input[type=text] and input[type=password].
我刚刚用 textareas 测试了它并且它有效!支持 textareas、input[type=text] 和 input[type=password] 的自动增长。
UPD.Looks like the original author removed the repo from github. The plugin hasn't been updated in a long while and turned out to be quite buggy. I can only suggest you to find a better solution. I made a pull request to this plugin sometime ago so I have a copy of itin my github account, use it only in case you want to improve it, it's not bulletproof!
更新。看起来原作者从 github 中删除了 repo。该插件已经很长时间没有更新了,结果证明它有很多问题。我只能建议您找到更好的解决方案。前段时间我向这个插件提出了一个拉取请求,所以我在我的 github 帐户中有一个它的副本,只有在你想改进它时才使用它,它不是防弹的!
Also, I found that ExtJS framework has autosize implementation for text fields, see the growconfig property. While it's not that easy to carve this little piece of logic out of the framework, it can give you some good ideas on the approach.
另外,我发现 ExtJS 框架对文本字段具有自动调整大小的实现,请参阅增长配置属性。虽然从框架中分割出这一小块逻辑并不容易,但它可以为您提供一些关于该方法的好主意。
回答by Racky
I was just thinking about the same thing. Textbox should resize it self as user is writing text into it. I never used it, but I have an idea how to do it. Something like this:
我只是在想同样的事情。当用户向其中写入文本时,文本框应自行调整大小。我从未使用过它,但我有一个想法。像这样的东西:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=windows-1250">
<meta name="generator" content="PSPad editor, www.pspad.com">
<title></title>
</head>
<body>
<table border="1">
<tr>
<td>
<span id="mySpan">
<span id="mySpan2"></span>
<input id="myText" type="text" style="width:100%" onkeyup="var span = document.getElementById('mySpan2');var txt = document.getElementById('myText'); span.innerHTML=txt.value;">
</span>
</td>
<td>
sss
</td>
</tr>
</table>
</body>
</html>
回答by user3470283
Try this code:
试试这个代码:
var newTextLength = Math.floor($("input#text).val() * .80);
$("input#text").attr("size",newTextLength);
回答by Powerlord
By default, input width is controlled by the sizeparameter, which for type="text"
corresponds to number of characters wide it should be.
默认情况下,输入宽度由size参数控制,它type="text"
对应于它应该是的字符数。
Since this is measured in characters and not pixels, the actual pixel size is controlled by the (fixed-width) font in use.
由于这是以字符而不是像素来衡量的,因此实际像素大小由使用的(固定宽度)字体控制。