jQuery - 自动大小文本输入(不是textarea!)[重复]

时间:2021-12-20 08:20:05

This question already has an answer here:

这个问题在这里已有答案:

How do I auto-resize the input type="text" field with jQuery? I want it to be like 100px wide at the start, then make it auto-widening as user inputs text... is that possible?

如何使用jQuery自动调整input type =“text”字段的大小?我希望它在开始时像100px宽,然后在用户输入文本时自动扩展...这可能吗?

9 个解决方案

#1


63  

Here's a plugin that'll do what you're after:

这是一个插件,它会做你想做的事情:

The plugin:

插件:

(function($){

$.fn.autoGrowInput = function(o) {

    o = $.extend({
        maxWidth: 1000,
        minWidth: 0,
        comfortZone: 70
    }, o);

    this.filter('input:text').each(function(){

        var minWidth = o.minWidth || $(this).width(),
            val = '',
            input = $(this),
            testSubject = $('<tester/>').css({
                position: 'absolute',
                top: -9999,
                left: -9999,
                width: 'auto',
                fontSize: input.css('fontSize'),
                fontFamily: input.css('fontFamily'),
                fontWeight: input.css('fontWeight'),
                letterSpacing: input.css('letterSpacing'),
                whiteSpace: 'nowrap'
            }),
            check = function() {

                if (val === (val = input.val())) {return;}

                // Enter new content into testSubject
                var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,' ').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                testSubject.html(escaped);

                // Calculate new width + whether to change
                var testerWidth = testSubject.width(),
                    newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
                    currentWidth = input.width(),
                    isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                         || (newWidth > minWidth && newWidth < o.maxWidth);

                // Animate width
                if (isValidWidthChange) {
                    input.width(newWidth);
                }

            };

        testSubject.insertAfter(input);

        $(this).bind('keyup keydown blur update', check);

    });

    return this;

};

})(jQuery);

EDIT: Found on: Is there a jQuery autogrow plugin for text fields?

编辑:发现:是否有文本字段的jQuery自动增长插件?

#2


10  

I don't think there is a perfect solution to that problem because you cannot detect the actual width of the text entered to the input element. It all depends of the font you are using, zoom settings in browser etc.

我不认为有一个完美的解决方案,因为你无法检测输入到输入元素的文本的实际宽度。这完全取决于您使用的字体,浏览器中的缩放设置等。

However if you can choose a font where you can actually calculate the number of pixels that text have (this is the hardest part but I guess you can try to estimate it somehow). You can use this to change the width of your input field.

但是,如果您可以选择一种字体,您可以实际计算文本所具有的像素数(这是最难的部分,但我想您可以尝试以某种方式估计它)。您可以使用它来更改输入字段的宽度。

 $('input').keyup(function () {
     // I'm assuming that 1 letter will expand the input by 10 pixels
     var oneLetterWidth = 10;

     // I'm also assuming that input will resize when at least five characters
     // are typed
     var minCharacters = 5;
     var len = $(this).val().length;
     if (len > minCharacters) {
         // increase width
         $(this).width(len * oneLetterWidth);
     } else {
         // restore minimal width;
         $(this).width(50);
     }
 });

#3


8  

(Edited: using the .text() method instead of .html() to get all formatting right.)

(编辑:使用.text()方法而不是.html()来获得所有格式。)

Hello I dont know if you are still looking but i came across this when i was looking for a script to do the same thing. So hope this helps anyone who is trying to do this, or something similar.

您好我不知道您是否还在寻找,但当我在寻找一个脚本来做同样的事情时,我遇到了这个问题。所以希望这可以帮助任何试图做到这一点的人,或类似的东西。

function editing_key_press(e){
    if(!e.which)editing_restore(this.parentNode);
    var text = $('<span>')
        .text($(this).val())
        .appendTo(this.parentNode);
    var w = text.innerWidth();
    text.remove();
    $(this).width(w+10);
}

The logic to this code is to put the content onto the page in a span and then gets the width of this content and removes it. The problem i did have was with it was that i had to get it to run on both keydown and keyup for it to work successfully.

此代码的逻辑是将内容放在跨度中的页面上,然后获取此内容的宽度并将其删除。我确实遇到的问题是我必须让它在keydown和keyup上运行才能成功运行。

Hope this helps, Might not as i have only been doing jquery for a short amount of time.

希望这会有所帮助,可能不会像我在短时间内只做jquery一样。

Thanks

谢谢

George

乔治

#4


6  

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

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

It uses the same approach as seize's answer but have some of the changes mentioned in the comments.

它使用与seize的答案相同的方法,但是在评论中提到了一些变化。

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

你可以在这里看到一个实例:http://jsfiddle.net/mJMpw/6/

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.

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

Of course you can also just initialize it using jQuery

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

$("selector").autosizeInput();

#5


2  

I used seize's answer, but made these changes:

我使用了seize的答案,但进行了以下更改:

  • Between setting isValidWidthChange and // Animate width:

    在设置isValidWidthChange和// Animate width之间:

    if (!isValidWidthChange && newWidth > minWidth && newWidth > o.maxWidth) {
        newWidth = o.maxWidth;
        isValidWidthChange = true;
    }
    

    This way the input will grow as big as you've allowed it when its contents are too big to fit within the max width.

    这样,当输入内容太大而无法容纳在最大宽度范围内时,输入将增大到您允许的大小。

  • After $(this).bind('keyup keydown blur update', check);:

    在$(this)之后.bind('keyup keydown blur update',check);:

    // Auto-size when page first loads
    check();
    

#6


1  

See this jQuery plugin: https://github.com/padolsey/jQuery.fn.autoResize

看到这个jQuery插件:https://github.com/padolsey/jQuery.fn.autoResize

I just tested it out with textareas and it works! Supports auto-growing of textareas, input[type=text] and input[type=password].

我刚用textareas测试它,它的工作原理!支持textareas的自动增长,输入[type = text]和输入[type = password]。

UPD. Looks like the original author removed the repo from github. The plugin hasn't been updated in a long while and turned out to be quite buggy. I can only suggest you to find a better solution. I made a pull request to this plugin sometime ago so I have a copy of it in my github account, use it only in case you want to improve it, it's not bulletproof!

UPD。看起来原作者从github中删除了repo。该插件在很长一段时间内没有更新,结果证明是非常错误的。我只能建议你找一个更好的解决方案。我前一段时间对这个插件发出了一个pull请求,所以我在我的github帐户中有一个副本,只有在你想改进的时候使用它,它不是防弹的!

Also, I found that ExtJS framework has autosize implementation for text fields, see the grow config property. While it's not that easy to carve this little piece of logic out of the framework, it can give you some good ideas on the approach.

此外,我发现ExtJS框架具有文本字段的自动调整实现,请参阅grow config属性。虽然从框架中删除这一小块逻辑并不容易,但它可以为您提供一些关于该方法的好主意。

#7


0  

By default, input width is controlled by the size parameter, which for type="text" corresponds to number of characters wide it should be.

默认情况下,输入宽度由size参数控制,对于type =“text”,它对应于应该是的宽字符数。

Since this is measured in characters and not pixels, the actual pixel size is controlled by the (fixed-width) font in use.

由于这是以字符而不是像素来衡量的,因此实际像素大小由使用中的(固定宽度)字体控制。

#8


0  

I was just thinking about the same thing. Textbox should resize it self as user is writing text into it. I never used it, but I have an idea how to do it. Something like this:

我只是想着同样的事情。当用户将文本写入文本框时,文本框应自行调整大小。我从来没用过它,但我知道怎么做。像这样的东西:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
  </head>
  <body>

  <table border="1">
  <tr>
    <td>
      <span id="mySpan">
        <span id="mySpan2"></span>
        <input id="myText" type="text" style="width:100%" onkeyup="var span = document.getElementById('mySpan2');var txt = document.getElementById('myText'); span.innerHTML=txt.value;">
       </span>
    </td>
    <td>
            sss
    </td>
  </tr>
</table>

  </body>
</html>

#9


0  

Try this code:

试试这段代码:

var newTextLength = Math.floor($("input#text).val() * .80);
$("input#text").attr("size",newTextLength);

#1


63  

Here's a plugin that'll do what you're after:

这是一个插件,它会做你想做的事情:

The plugin:

插件:

(function($){

$.fn.autoGrowInput = function(o) {

    o = $.extend({
        maxWidth: 1000,
        minWidth: 0,
        comfortZone: 70
    }, o);

    this.filter('input:text').each(function(){

        var minWidth = o.minWidth || $(this).width(),
            val = '',
            input = $(this),
            testSubject = $('<tester/>').css({
                position: 'absolute',
                top: -9999,
                left: -9999,
                width: 'auto',
                fontSize: input.css('fontSize'),
                fontFamily: input.css('fontFamily'),
                fontWeight: input.css('fontWeight'),
                letterSpacing: input.css('letterSpacing'),
                whiteSpace: 'nowrap'
            }),
            check = function() {

                if (val === (val = input.val())) {return;}

                // Enter new content into testSubject
                var escaped = val.replace(/&/g, '&amp;').replace(/\s/g,' ').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                testSubject.html(escaped);

                // Calculate new width + whether to change
                var testerWidth = testSubject.width(),
                    newWidth = (testerWidth + o.comfortZone) >= minWidth ? testerWidth + o.comfortZone : minWidth,
                    currentWidth = input.width(),
                    isValidWidthChange = (newWidth < currentWidth && newWidth >= minWidth)
                                         || (newWidth > minWidth && newWidth < o.maxWidth);

                // Animate width
                if (isValidWidthChange) {
                    input.width(newWidth);
                }

            };

        testSubject.insertAfter(input);

        $(this).bind('keyup keydown blur update', check);

    });

    return this;

};

})(jQuery);

EDIT: Found on: Is there a jQuery autogrow plugin for text fields?

编辑:发现:是否有文本字段的jQuery自动增长插件?

#2


10  

I don't think there is a perfect solution to that problem because you cannot detect the actual width of the text entered to the input element. It all depends of the font you are using, zoom settings in browser etc.

我不认为有一个完美的解决方案,因为你无法检测输入到输入元素的文本的实际宽度。这完全取决于您使用的字体,浏览器中的缩放设置等。

However if you can choose a font where you can actually calculate the number of pixels that text have (this is the hardest part but I guess you can try to estimate it somehow). You can use this to change the width of your input field.

但是,如果您可以选择一种字体,您可以实际计算文本所具有的像素数(这是最难的部分,但我想您可以尝试以某种方式估计它)。您可以使用它来更改输入字段的宽度。

 $('input').keyup(function () {
     // I'm assuming that 1 letter will expand the input by 10 pixels
     var oneLetterWidth = 10;

     // I'm also assuming that input will resize when at least five characters
     // are typed
     var minCharacters = 5;
     var len = $(this).val().length;
     if (len > minCharacters) {
         // increase width
         $(this).width(len * oneLetterWidth);
     } else {
         // restore minimal width;
         $(this).width(50);
     }
 });

#3


8  

(Edited: using the .text() method instead of .html() to get all formatting right.)

(编辑:使用.text()方法而不是.html()来获得所有格式。)

Hello I dont know if you are still looking but i came across this when i was looking for a script to do the same thing. So hope this helps anyone who is trying to do this, or something similar.

您好我不知道您是否还在寻找,但当我在寻找一个脚本来做同样的事情时,我遇到了这个问题。所以希望这可以帮助任何试图做到这一点的人,或类似的东西。

function editing_key_press(e){
    if(!e.which)editing_restore(this.parentNode);
    var text = $('<span>')
        .text($(this).val())
        .appendTo(this.parentNode);
    var w = text.innerWidth();
    text.remove();
    $(this).width(w+10);
}

The logic to this code is to put the content onto the page in a span and then gets the width of this content and removes it. The problem i did have was with it was that i had to get it to run on both keydown and keyup for it to work successfully.

此代码的逻辑是将内容放在跨度中的页面上,然后获取此内容的宽度并将其删除。我确实遇到的问题是我必须让它在keydown和keyup上运行才能成功运行。

Hope this helps, Might not as i have only been doing jquery for a short amount of time.

希望这会有所帮助,可能不会像我在短时间内只做jquery一样。

Thanks

谢谢

George

乔治

#4


6  

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

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

It uses the same approach as seize's answer but have some of the changes mentioned in the comments.

它使用与seize的答案相同的方法,但是在评论中提到了一些变化。

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

你可以在这里看到一个实例:http://jsfiddle.net/mJMpw/6/

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.

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

Of course you can also just initialize it using jQuery

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

$("selector").autosizeInput();

#5


2  

I used seize's answer, but made these changes:

我使用了seize的答案,但进行了以下更改:

  • Between setting isValidWidthChange and // Animate width:

    在设置isValidWidthChange和// Animate width之间:

    if (!isValidWidthChange && newWidth > minWidth && newWidth > o.maxWidth) {
        newWidth = o.maxWidth;
        isValidWidthChange = true;
    }
    

    This way the input will grow as big as you've allowed it when its contents are too big to fit within the max width.

    这样,当输入内容太大而无法容纳在最大宽度范围内时,输入将增大到您允许的大小。

  • After $(this).bind('keyup keydown blur update', check);:

    在$(this)之后.bind('keyup keydown blur update',check);:

    // Auto-size when page first loads
    check();
    

#6


1  

See this jQuery plugin: https://github.com/padolsey/jQuery.fn.autoResize

看到这个jQuery插件:https://github.com/padolsey/jQuery.fn.autoResize

I just tested it out with textareas and it works! Supports auto-growing of textareas, input[type=text] and input[type=password].

我刚用textareas测试它,它的工作原理!支持textareas的自动增长,输入[type = text]和输入[type = password]。

UPD. Looks like the original author removed the repo from github. The plugin hasn't been updated in a long while and turned out to be quite buggy. I can only suggest you to find a better solution. I made a pull request to this plugin sometime ago so I have a copy of it in my github account, use it only in case you want to improve it, it's not bulletproof!

UPD。看起来原作者从github中删除了repo。该插件在很长一段时间内没有更新,结果证明是非常错误的。我只能建议你找一个更好的解决方案。我前一段时间对这个插件发出了一个pull请求,所以我在我的github帐户中有一个副本,只有在你想改进的时候使用它,它不是防弹的!

Also, I found that ExtJS framework has autosize implementation for text fields, see the grow config property. While it's not that easy to carve this little piece of logic out of the framework, it can give you some good ideas on the approach.

此外,我发现ExtJS框架具有文本字段的自动调整实现,请参阅grow config属性。虽然从框架中删除这一小块逻辑并不容易,但它可以为您提供一些关于该方法的好主意。

#7


0  

By default, input width is controlled by the size parameter, which for type="text" corresponds to number of characters wide it should be.

默认情况下,输入宽度由size参数控制,对于type =“text”,它对应于应该是的宽字符数。

Since this is measured in characters and not pixels, the actual pixel size is controlled by the (fixed-width) font in use.

由于这是以字符而不是像素来衡量的,因此实际像素大小由使用中的(固定宽度)字体控制。

#8


0  

I was just thinking about the same thing. Textbox should resize it self as user is writing text into it. I never used it, but I have an idea how to do it. Something like this:

我只是想着同样的事情。当用户将文本写入文本框时,文本框应自行调整大小。我从来没用过它,但我知道怎么做。像这样的东西:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=windows-1250">
  <meta name="generator" content="PSPad editor, www.pspad.com">
  <title></title>
  </head>
  <body>

  <table border="1">
  <tr>
    <td>
      <span id="mySpan">
        <span id="mySpan2"></span>
        <input id="myText" type="text" style="width:100%" onkeyup="var span = document.getElementById('mySpan2');var txt = document.getElementById('myText'); span.innerHTML=txt.value;">
       </span>
    </td>
    <td>
            sss
    </td>
  </tr>
</table>

  </body>
</html>

#9


0  

Try this code:

试试这段代码:

var newTextLength = Math.floor($("input#text).val() * .80);
$("input#text").attr("size",newTextLength);