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

后端 未结 10 1363
挽巷
挽巷 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:51

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

    So i made an example where it tries to calculate the width by inserting letters in a span and calculating there width

    (function() {
        var mDiv = $("").text("M").appendTo("body"),
            mSize = mDiv.width();
        mDiv.detach();
    
        var letterSize = function(s) {
            var sDiv = $("").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 });
        });
    } ());
    

    Theres probably a much better way of doing this.

提交回复
热议问题