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

mig*_*jek 40 html jquery input

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

小智 64

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

插件:

(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);
Run Code Online (Sandbox Code Playgroud)

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

  • Downvoted -1 [这是其他人的答案的精确剪切/粘贴](http://stackoverflow.com/questions/931207/is-there-a-jquery-autogrow-plugin-for-text-fields).另外,**demo(也不是OP)是使用free/anon jsbin帐户创建的,并且已经超时 - 不再可用.***请改用jsFiddle.* (7认同)
  • 只是一个观察,这个插件在粘贴文本时不起作用,并且还阻止用户按下并按住一个键. (3认同)

RaY*_*ell 10

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

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

 $('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);
     }
 });
Run Code Online (Sandbox Code Playgroud)


小智 8

(编辑:使用.text()方法而不是.html()使所有格式正确.)

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

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);
}
Run Code Online (Sandbox Code Playgroud)

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

希望这会有所帮助,可能不是因为我只在短时间内做了jquery.

谢谢

乔治

  • 我喜欢它,但在输入空格时它不起作用. (2认同)

Mar*_*inF 6

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

它使用与seize的答案相同的方法,但有一些在评论中提到的更改.

你可以在这里看到一个实例: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;    
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

$("selector").autosizeInput();
Run Code Online (Sandbox Code Playgroud)

  • 你的小提琴示例在 chrome 中不起作用:-( (2认同)