如果我的价值是 xyz
我不希望输入宽度 = 100% 我希望输入宽度会自动调整大小等于输入值中的字数。
有点hacky,但我发现以下是一种可能的方法:
示例标记:
<input />
<span id="input-width-helper"></span>
CSS:
input {
min-width: 20px;
width: 20px;
}
#input-width-helper {
position: absolute;
visibility: hidden;
/* extra styles would be needed, if the input has other styles
affecting it's font, width, etc. */
}
js:
$('input').on('keydown', function () {
var
$this = $(this),
$helper = $('#input-width-helper');
setTimeout(function () {
// the '+ 10' here is arbitrary to account for paddings/borders
// if the hidden helper ('#input-width-helper') is styled correctly,
// this could probably be removed
$this.css('width', $helper.text($this.val()).width() + 10);
}, 0);
});
演示:http: //jsbin.com/aqakus/3/
注意:当然,这需要熟练使用多个输入!