jQuery - 根据值的宽度调整表单输入的大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9328682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:39:58  来源:igfitidea点击:

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

jqueryformsinputresize

提问by Wordpressor

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/

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

采纳答案by David Laberge

Here is the jQuery code :

这是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/

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

回答by MartinF

I have a jQuery plugin on GitHub: https://github.com/MartinF/jQuery.Autosize.Input

我在 GitHub 上有一个 jQuery 插件:https: //github.com/MartinF/jQuery.Autosize.Input

It mirrors the value of the input so it can calculate the actual length instead of guessing or other approaches mentioned.

它反映了输入的值,因此它可以计算实际长度,而不是猜测或提到的其他方法。

You can see an live example here: http://jsfiddle.net/jw9oqz0e/

你可以在这里看到一个活生生的例子:http: //jsfiddle.net/jw9oqz0e/

Example:

例子:

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

You just use css to set min/max-width and use a transition on the width if you want a nice effect.

如果你想要一个好的效果,你只需使用 css 来设置最小/最大宽度并在宽度上使用过渡。

You can specify the space / distance to the end as the value in json notation for the data-autosize-input attribute on the input element.

您可以为 input 元素上的 data-autosize-input 属性指定到末尾的空间/距离作为 json 表示法中的值。

Of course you can also just initialize it using jQuery

当然你也可以使用jQuery初始化它

$("selector").autosizeInput();

回答by Ahmed-Anas

Current answers were waay to complicated. Heres a quick one

目前的答案很复杂。这是一个快速的

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

Adding the above to input keydown/up/press events is trivial. Tested in chrome

将上述内容添加到输入 keydown/up/press 事件是微不足道的。在铬中测试

回答by Yorgo

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

回答by Manse

Something 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
});?

You could change the multiplier on personal preference / text-size

您可以根据个人喜好/文本大小更改乘数

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

示例:http: //jsfiddle.net/bzBdX/6/

回答by Manish Gupta

As mentioned by @ManseUK. This line worked for me. JQuery version 1.8

正如@ManseUK 所提到的。这条线对我有用。jQuery 1.8 版

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

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

回答by Alexandr K

All those solutions based on number of characters are quite weak, because each character could be of a different width if it is not a monotype font. I'm solving this problem with creating a div containing value of text input with the same font properties and getting its width as a required one.

所有这些基于字符数的解决方案都非常薄弱,因为如果每个字符不是单一字体,则它的宽度可能不同。我正在通过创建一个包含具有相同字体属性的文本输入值的 div 并将其宽度作为必需的宽度来解决这个问题。

Something like this:

像这样的东西:

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

回答by megakorre

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

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

Theres probably a much better way of doing this.

可能有更好的方法来做到这一点。

回答by ImmortalPC

this example as been tested on Chrome 25 and Firefox 19. (http://jsfiddle.net/9ezyz/)

此示例已在 Chrome 25 和 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);

回答by Ninad Ajnikar

You can check this demo on js fiddle ... http://jsfiddle.net/ninadajnikar/bzBdX/9/.

您可以在 js fiddle ... http://jsfiddle.net/ninadajnikar/bzBdX/9/上查看此演示。

You update the width values as you like it

您可以根据需要更新宽度值