2012-02-17 14 views

Respuesta

8

Aquí está th E Código jQuery:

$('input').each(function(){ 
var value = $(this).val(); 
var size = value.length; 
// playing with the size attribute 
//$(this).attr('size',size); 

// playing css width 
size = size*2; // average width of a char 
$(this).css('width',size*3); 

})​; 

http://jsfiddle.net/bzBdX/7/

+0

Esto no está funcionando en jsfiddle, considere agregar la función 'keydown' para escuchar las pulsaciones de teclas –

1

Algo simple:

$('#resizeme').keydown(function(){ // listen for keypresses 
var contents = $(this).val();  // get value 
var charlength = contents.length; // get number of chars 
newwidth = charlength*9;   // rough guesstimate of width of char 
$(this).css({width:newwidth});  // apply new width 
});​ 

Se podría cambiar el multiplicador de la preferencia personal/de texto de tamaño

Ejemplo: http://jsfiddle.net/bzBdX/6/

1
$(function(){ 
    $("input").keyup(function(){ 
     $(this).stop().animate({ 
     width: $(this).val().length*7 
    },100)     
    }) 
})​ 
+0

'length * 7'? Has usado este método (http://xkcd.com/221/) para calcularlo? –

1

http://jsfiddle.net/bzBdX/11/

así que hice un ejemplo en el que trata de calcular el ancho de letras inserción en un lapso y calculando hay anchura

(function() { 
    var mDiv = $("<span />").text("M").appendTo("body"), 
     mSize = mDiv.width(); 
    mDiv.detach(); 

    var letterSize = function(s) { 
     var sDiv = $("<span />").text("M" + s + "M").appendTo("body"), 
      sSize = sDiv.width(); 

     sDiv.detach(); 

     return (sSize - (mSize * 2)) * 0.89; 
    }; 

    $("input[data-resise-me]").each(function() { 
     var minSize = $(this).width(); 

     var resizeInput = function() { 
      var calcSize = $.map($(this).val(), letterSize); 
      var inputSize = 0; 
      $.each(calcSize, function(i, v) { inputSize += v; }); 

      $(this).width(inputSize < minSize ? minSize : inputSize); 
     }; 

     $(this).on({ keydown: resizeInput, keyup: resizeInput }); 
    }); 
}()); 

Hay probablemente una forma mucho mejor de hacerlo.

+1

¿Por qué multiplicas por 0.89? –

0

este ejemplo como ha probado en Chrome 25 y Firefox 19. (http://jsfiddle.net/9ezyz/)

function input_update_size() 
{ 
    var value = $(this).val(); 
    var size = 12; 

    // Looking for font-size into the input 
    if (this.currentStyle) 
     size = this.currentStyle['font-size']; 
    else if (window.getComputedStyle) 
     size = document.defaultView.getComputedStyle(this,null).getPropertyValue('font-size'); 
    $(this).stop().animate({width:(parseInt(size)/2+1)*value.length},500); 
    //$(this).width((parseInt(size)/2+1)*value.length); 
} 

$('input') 
    .each(input_update_size) 
    .keyup(input_update_size); 
9

I tiene un plugin jQuery en GitHub: https://github.com/MartinF/jQuery.Autosize.Input

que refleja el valor de la entrada para que pueda calcular la longitud real en lugar de adivinar u otros enfoques mencionados.

Se puede ver un ejemplo vivo aquí: http://jsfiddle.net/mJMpw/6/

Ejemplo:

<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;  
} 

Usted sólo tiene que utilizar CSS para definir min/max-width y utilizar una transición de la anchura si quieres un bonito efecto .

Puede especificar el espacio/distancia hasta el final como el valor en notación json para el atributo data-autosize-input en el elemento de entrada.

Por supuesto, también puede simplemente inicializarlo usando jQuery

$("selector").autosizeInput(); 
1

Según lo mencionado por @ManseUK. Esta línea funcionó para mí. JQuery versión 1.8

$ ('# resizeme').css ({ancho: newwidth});

1

Todas esas soluciones basadas en el número de caracteres son bastante débiles, porque cada carácter podría tener un ancho diferente si no es una fuente de monotipo. Estoy solucionando este problema con la creación de un div que contiene el valor de entrada de texto con las mismas propiedades de fuente y obteniendo su ancho como uno requerido.

Algo como esto:

function resizeInput() { 
    $('body').append('<div class="new_width">'+$(this).val()+'</div>'); 
    $(this).css('width', $('.new_width').width()); 
    $('.new_width').remove() 
} 
$('input') 
    // event handler 
    .keyup(resizeInput) 
    // resize on page load 
    .each(resizeInput); 
4

respuestas actuales eran waay a complicado. He aquí uno rápido

$('#myinput').width($('#myinput').prop('scrollWidth')) 

Agregar lo anterior a los eventos de entrada/salida/prensa es trivial. Probado en Chrome

+0

Técnicamente la pregunta mencionó jquery. Sin embargo, esta es la mejor solución al problema. Rgds –

Cuestiones relacionadas