【问题标题】:Is there a jQuery autogrow plugin for text fields?是否有用于文本字段的 jQuery 自动增长插件?
【发布时间】:2010-10-30 04:39:24
【问题描述】:

我找到了各种用于自动增长 textarea 的插件,但没有输入文本字段。有人知道有没有吗?

【问题讨论】:

  • 澄清一下:您是否正在寻找当文本即将变得对于文本字段而言太大时,该字段会不断扩大以一次显示所有文本的人?

标签: javascript jquery scripting


【解决方案1】:

如果您希望文本框在其中的字符串超出其宽度时增长,也许这样的东西对您有用...它检测文本框的大小属性。如果字符串的长度超过该属性,它会将文本框扩展到 keyup 上的字符串长度。

在下面的脚本中,“#test”是一个文本框 ID。

<script language="javascript" type="text/javascript">
$(document).ready(function(){
    $("#test").keyup(function(){
        if($("#test").attr("size") < $("#test").val().length){
            size = $("#test").val().length;
            $("#test").attr("size",size);
        }
    })
});
</script>

【讨论】:

  • 这依赖于文本是固定宽度的字体;所以它不适用于 Arial、verdana 等字体。
【解决方案2】:

这是一个插件,可以满足您的需求:

编辑:我已根据 Mathias 的评论修复了插件。 :)

在此处查看演示:http://jsfiddle.net/rRHzY

插件:

(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,'&nbsp;').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);

【讨论】:

  • 很棒的插件,詹姆斯!不过有一个建议:如果 INPUT 在删除文本时也会减小大小,那可能会很酷。
  • 感谢马蒂亚斯;刚刚修复它 - 它现在应该按预期减少:)
  • 完美!你完全应该在博客上写这个。
  • 太棒了!这完全是我一直在寻找的东西,你绝对应该在博客上写下这个并获得一些链接诱饵,以便其他人可以在 Google 中找到它。
  • 邪恶的剧本,詹姆斯!不知道我是否会使用它,但自从我上次感受到美妙的 javascript 所创造的那种喜悦之情已经有一段时间了!
【解决方案3】:

好插件,谢谢!不过,我更改了两个在我的项目中似乎效果更好的东西。

  1. 我将 TESTER 标记更改为 DIV,以避免出现“意外调用方法或属性访问”。在 IE8 中(即使您的演示确实在 IE8 中工作。使用自定义 HTML 标记是否有特殊原因?
  2. 在接近代码末尾的绑定语句之后,我添加了对 check() 的调用,以便在加载页面后立即调整文本框的大小,以防文本框在启动时已经包含内容。

希望这会有所帮助。

【讨论】:

  • 最后也使用了 check()
  • 当我在加载页面后运行检查功能时没有任何反应,但是 onblur、onkeyup 等它工作正常。有人知道为什么吗?
【解决方案4】:

只是想分享对 James 的出色插件的一个小改进。将此代码添加到 tester 元素的 CSS 声明中以说明 text-indent:

textIndent: 0

没有它,在某些情况下,tester 元素可能会无意中从其他地方继承文本缩进,从而丢弃输入的大小。

和 JP 一样,我也想从一开始就将输入调整为正确的大小,我的做法略有不同,将“trigger('keyup')”链接到 autoGrowInput 方法调用,例如:

$('#contact_form').autoGrowInput({comfortZone: 7, minWidth: 10, maxWidth: 200}).trigger('keyup');

作为旁注,我注册这个网站纯粹是为了评论 James 的解决方案,我有点恼火地发现我不能,因为我没有足够的声望点来开始。抱歉,如果我遗漏了什么,但这似乎意味着我必须发表这是对主要问题的评论,而不是更恰当地评论 James 的解决方案。

【讨论】:

    【解决方案5】:

    我也换了

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

    $(this).bind('keyup blur update', check).bind('keydown', function() {
        setTimeout(check);
    });
    

    为了在浏览器重新渲染字段后立即调整其大小。它会让这个领域摆脱一些喋喋不休。

    【讨论】:

      【解决方案6】:

      有趣的是,IE 溢出:可见被非常重视。您可以通过在输入元素上应用溢出:可见来实现此效果。不确定现代浏览器是否存在任何类似的 CSS 技巧。

      【讨论】:

        【解决方案7】:

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

        它使用与 James 回答相同的方法,但在 cmets 中提到了一些变化。

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

        例子:

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

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

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

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

        $("selector").autosizeInput();
        

        【讨论】:

          【解决方案8】:

          很棒的插件詹姆斯!谢谢。我确实添加了 JP 最后的检查建议,虽然非常有效。

          我还添加了一些更改。 如果更改的宽度超过 maxWidth,我想将输入的大小设置为最大大小,所以我添加了:

          else if (widthexceeds){
              input.width(o.maxWidth);
          }
          

          在 if 检查 isValidWidthChange 的下方 widthexceeds = newWidth &gt; o.maxWidth

          【讨论】:

            【解决方案9】:

            我为文本类型的输入创建了一个插件,它重新创建了这种行为。它还有一些其他独特的功能。您可以看到example 并查看插件的documentation。 @james 回答在将大文本粘贴到输入时存在一些问题。为了解决这个问题,我对他的代码做了一些修改。这是一个demo,用于此示例。

            (function($){        
                $.fn.autoGrowInput = function(o) {
            
                    o = $.extend({
                        maxWidth: 200,
                        minWidth: 1,
                        comfortZone: 1,
                      width: 1
                    }, o);
            
                    this.filter('input:text').each(function(){
            
                        var minWidth = o.minWidth || $(this).width(),
                            maxWidth = o.maxWidth,
                            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,'&nbsp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
                                testSubject.html(escaped);
            
                                // Calculate new width + whether to change
                                var testerWidth = testSubject.width(),
                                newWidth = testerWidth + o.comfortZone,
                                currentWidth = input.width();
            
                               if (testerWidth < minWidth) {
                                   newWidth = minWidth;
                               } else if (testerWidth > maxWidth) {
                                   newWidth = maxWidth;
                               } 
            
                               input.width(newWidth + o.comfortZone);  
                        };
            
                        testSubject.insertAfter(input);
            
                        $(this).bind('input', check);
            
                    });
            
                    return this;
            
                };
            
            })(jQuery);
            

            【讨论】:

            • “输入”事件太棒了!请注意:该事件在 IE 中无法正常工作:在 IE9 中删除字符不会触发此事件,旧版本根本没有。
            【解决方案10】:

            我创建了一个名为input-autogrow 的插件来为我自己的项目解决这个问题。这个插件最初是基于 James 的回答,但在很多方面都得到了改进。

            https://github.com/westonganger/input-autogrow

            input-autogrow 是一个用于自动增长输入的插件。这个插件与其他插件不同,因为大多数情况下都是针对 textarea 标签,而这个库是针对输入标签的。需要 DOM 库,例如 jQuery、Zepto 或任何支持 $.fn 插件的库。

            这里有一些用法示例。

            /* Makes elements readonly if they already have the readonly attribute */
            $('input.autogrow').inputAutogrow();
            
            /* Manually trigger update */
            $('input.autogrow').trigger('autogrow');
            /* or */
            $('input.autogrow').trigger('change');
            
            /* Custom Options */
            $('input.autogrow').inputAutogrow({maxWidth: 500, minWidth: 25, trailingSpace: 10});
            
            /* Remove autogrow from input */
            $('input.autogrow').inputAutogrow('destroy');
            

            【讨论】:

              猜你喜欢
              • 2011-06-24
              • 1970-01-01
              • 2012-11-04
              • 2011-07-23
              • 1970-01-01
              • 1970-01-01
              • 2010-11-20
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多