当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Resize input to fit its content

问题描述:

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 input to get bigger if user types over the right border.

网友答案:

Maybe someone else has a better way, but you could try this:

Example: 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.

Probably works best with a fixed width font:

input {
    font-family:Courier;
}
网友答案:

Let the browser do the calculating of the width by using a div with contenteditable set 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

网友答案:

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).

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: