jQuery - resizing form input based on value's width?

后端 未结 10 1227
挽巷
挽巷 2020-12-06 17:28

Is it possible to get input\'s value width and resize the input dynamically so the value will fit?

Here\'s an example:

http://jsfiddle.net/bzBdX/2/

10条回答
  •  有刺的猬
    2020-12-06 17:44

    this example as been tested on Chrome 25 and 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);
    

提交回复
热议问题