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

标签 jquery html input

<分区>

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

最佳答案

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

插件:

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

编辑: 发现于:Is there a jQuery autogrow plugin for text fields?

关于jQuery - 自动调整大小的文本输入(不是 textarea!),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1288297/

相关文章:

javascript - 我想使用 jquery 将输入值存储在数组中

html - 即使我禁用了所有相关的 CSS,我网站上链接下的蓝线?

c# - 快速将字符串复制到字符数组

javascript - 使用javascript发送带有表单的单个隐藏字段

javascript - 在 jQuery 中将 live() 变成 on()

javascript - @jQuery 中字符串的符号

javascript - 无法在 jquery php codeigniter 中获取动态创建的输入字段值

Python - Web 抓取 HTML 表并打印到 CSV

file - FFMPEG 从文本文件中读取输入并同时从文件中过滤复杂

javascript - 如何根据背景图像的高度和宽度设置DIV尺寸