javascript 调整输入大小以适合其内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4663716/
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
Resize input to fit its content
提问by rsk82
I do not care for a specific technology, it could be JS, CSS or even some unstandard and evil html attributes. I just want the inputto get bigger if user types over the right border.
我不关心特定的技术,它可能是 JS、CSS 甚至一些不标准和邪恶的 html 属性。input如果用户在右边框上键入,我只是想让它变大。
采纳答案by user113716
Maybe someone else has a better way, but you could try this:
也许其他人有更好的方法,但你可以试试这个:
Example:http://jsfiddle.net/aAueA/1/
示例:http : //jsfiddle.net/aAueA/1/
var input = document.getElementsByTagName('input')[0];
input.onkeypress = input.onkeydown = function() {
this.size = ( this.value.length > 10 ) ? this.value.length : 10;
};
This sets it at a minimum size of 10 and expands if you go beyond 10 characters.
这将其设置为 10 的最小大小,如果超过 10 个字符,则会扩展。
Probably works best with a fixed width font:
使用固定宽度的字体可能效果最好:
input {
font-family:Courier;
}
回答by Erik Aigner
Let the browser do the calculating of the width by using a divwith contenteditableset to true.
让浏览器通过使用divwith contenteditableset to 来计算宽度true。
<div class="pseudo-input" contenteditable="true">Resizes to my content!</div>
There should be no issues with browser support http://caniuse.com/#feat=contenteditable
浏览器支持应该没有问题http://caniuse.com/#feat=contenteditable
回答by Тёма Пендюрин
You can also create div element, copy your input style to it and use it's dimensions to resize input. (Chosen multiple uses this solution).
您还可以创建 div 元素,将您的输入样式复制到它并使用它的尺寸来调整输入的大小。(选择多个使用此解决方案)。
var input = $('input'),
dummy = $('<div style="position:absolute; left: -1000%;">').appendTo('body');
['font-size', 'font-style', 'font-weight', 'font-family',
'line-height', 'text-transform', 'letter-spacing'].forEach(function(index) {
dummy.css(index, input.css(index));
});
input.on('input', function() {
dummy.html(this.value);
input.width(dummy.width());
});
UPD: better to use pre instead div to follow spaces size.
UPD:最好使用 pre 而不是 div 来跟随空格大小。

