2012-02-17 15 views

risposta

8

Ecco th e codice 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

Questo non sta lavorando su jsfiddle, perche la funzione aggiunta di 'KeyDown' per ascoltare la pressione dei tasti –

1

Qualcosa di semplice:

$('#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 
});​ 

Si potrebbe cambiare il moltiplicatore delle preferenze personali/text-size

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

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

'lunghezza * 7'? Hai usato [questo] (http://xkcd.com/221/) metodo per calcolarlo? –

1

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

così ho fatto un esempio in cui si cerca di calcolare la larghezza da lettere inserimento in un arco e calcolando c'è larghezza

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

C'è probabilmente un modo migliore per farlo.

+1

Perché moltiplichi per 0.89? –

0

questo esempio come stato testato su Chrome 25 e 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

Ho un plugin per jQuery su GitHub: https://github.com/MartinF/jQuery.Autosize.Input

rispecchia il valore dell'ingresso in modo da poter calcolare la lunghezza effettiva invece di indovinare o altri approcci menzionati.

È possibile vedere un esempio vivo qui: http://jsfiddle.net/mJMpw/6/

Esempio:

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

Basta usare i CSS per impostare min/max-width e utilizzare una transizione dalla larghezza se si desidera un piacevole effetto .

È possibile specificare lo spazio/distanza fino alla fine come valore in notazione json per l'attributo immissione dati autosize sull'elemento di input.

Naturalmente si può anche solo inizializzare utilizzando jQuery

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

Come già detto da @ManseUK. Questa linea ha funzionato per me. JQuery versione 1.8

$ ('# risizeme').css ({width: newwidth});

1

Tutte quelle soluzioni basate sul numero di caratteri sono piuttosto deboli, poiché ogni carattere può avere una larghezza diversa se non è un font monotype. Sto risolvendo questo problema creando un div contenente il valore di input di testo con le stesse proprietà del font e ottenendo la sua larghezza come richiesto.

Qualcosa di simile a questo:

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

risposte attuali erano waay a complicate. Ecco una rapida

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

Aggiunta di quanto sopra per inserire keydown/up/premere eventi è banale. Testato in cromo

+0

Tecnicamente la domanda cita jquery. Tuttavia questa è la migliore soluzione al problema. Rgds –

Problemi correlati