【问题标题】:Dynamically expand height of input type "text" based on number of characters typed into field根据输入字段的字符数动态扩展输入类型“文本”的高度
【发布时间】:2014-05-22 22:30:53
【问题描述】:

类似于下面的 JSFiddle(我收藏了它,不知道最初的问题是从哪里出现的):

http://jsfiddle.net/mJMpw/6/

<input type="text" value="" placeholder="Autosize" data-autosize-input='{ "space": 10 }' />

input {
    width: 200px;
    min-width: 200px;
    max-width: 300px;
    transition: width 0.25s;    
}

有没有办法将文本字段的宽度固定为,例如仅 200 像素,并且如果用户添加更多,文本字段的 高度 会增加比 200px 能够包含的文本?如果用户需要更多的输入空间,我希望添加更多的行...所以我需要 height,而不是宽度来动态调整大小。

谢谢!

【问题讨论】:

  • 你的意思是textarea? flaviusmatis.github.io/flexibleArea.js
  • 嗨。不,不是 textarea ...我想知道单行 input type="text" 是否能够增长(类似于 textarea)。不过,也许 textarea 是唯一的出路吗?也许 textarea 是一个解决方案,但它是否可以在开始时看起来像一个常规文本字段?
  • 可以肯定的是,您不能使用多行输入类型的文本,这就是 textarea 的用途。您可以修改textarea 使其看起来像一个输入字段。

标签: javascript jquery css forms


【解决方案1】:

更新[2]:

由于scrollHeight总是等于height,我们必须在scrollHeight之前将height设置为'1',然后当我们删除字符时&lt;textarea&gt;自动调整:

$('textarea').on('keydown', function(e){
    if(e.which == 13) {e.preventDefault();}
}).on('input', function(){
    $(this).height(1);
    var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
    $(this).height(totalHeight);
});

小提琴:

http://jsfiddle.net/mJMpw/551/

更新:

正如朋友所说,&lt;input type="text"/&gt; 没有换行符。我建议使用&lt;textarea&gt; 是:

$('textarea').on({input: function(){
    var totalHeight = $(this).prop('scrollHeight') - parseInt($(this).css('padding-top')) - parseInt($(this).css('padding-bottom'));
    $(this).css({'height':totalHeight});
}
});

小提琴:

http://jsfiddle.net/mJMpw/548/

原始答案:

这很丑,但你可以这样做:

$('input[type="text"]').on('keyup',function(){
    var text = $(this).val();
    var getWidth = $('<span class="getWidth" style="white-space:nowrap; width:auto;">' + text + '</span>').insertAfter(this);
    $(this).css({'width':getWidth.outerWidth()}).next('.getWidth').remove();
});

您必须为 .getWidth 指定相同的字体/填充属性并输入:

input, .getWidth {
    font-family:arial;
    font-size:12px;
    font-weight:normal;
    letter-spacing:normal;
    padding:3px;
}

小提琴:

http://jsfiddle.net/9SMRf/

【讨论】:

  • 谢谢...但是,我实际上希望扩展文本字段的 高度
  • @Berklie jsfiddle.net/APe4V 正如其他人所说,这不可能。输入字段中不能有换行符。
  • 好吧,为更新后的代码 +1,但看起来它只能增长,不能缩小。
  • @KingKing 您好,感谢您的观察。我刚刚修好了。这是因为 scrollHeight 总是等于高度。那么我们必须在设置scrollHeight之前设置高度'1'。 jsfiddle.net/mJMpw/551
  • @LGVentura 很好,看起来这是我无法相信的最佳方法。尽管使用一些虚拟元素的技术(如我的回答所示)是众所周知的,有时是唯一可能的方法,但在这种情况下,它还有很长的路要走。事实上height 可以重置为01em 之间的任何值,非常有趣的解决方案。这应该被 OP 接受为答案。
【解决方案2】:

正如其他人解释的那样,input 字段不能有多行文本,您应该使用 textarea 模拟输入字段,并使用 jQuery 使其垂直自动调整大小(固定宽度)。

JS

//This span is used to measure the size of the textarea
//it should have the same font and text with the textarea and should be hidden
var span = $('<span>').css('display','inline-block')
                      .css('word-break','break-all')
                      .appendTo('body').css('visibility','hidden');
function initSpan(textarea){
  span.text(textarea.text())
      .width(textarea.width())
      .css('font',textarea.css('font'));
}
$('textarea').on({
    input: function(){
       var text = $(this).val();      
       span.text(text);      
       $(this).height(text ? span.height() : '1.1em');
    },
    focus: function(){           
       initSpan($(this));
    },
    keypress: function(e){
       //cancel the Enter keystroke, otherwise a new line will be created
       //This ensures the correct behavior when user types Enter 
       //into an input field
       if(e.which == 13) e.preventDefault();
    }
});

CSS

textarea {
  width:200px;
  resize:none;
  overflow:hidden;
  font-size:18px;
  height:1.1em;
  padding:2px;
}

Demo.

更新演示:

这个新更新的demo修复了一些bug,还支持回车键,最大高度限制,宽度一开始不需要固定设置(我们可以设置它的最小宽度)。它功能更全面。

Updated Demo

【讨论】:

    【解决方案3】:

    不是我的,但效果很好:

    CSS

    textarea {
         color: #444;
         padding: 5px;
    }
    .txtstuff {
        resize: none;
        overflow: hidden;
    }
    .hiddendiv {
        display: none;
        white-space: pre-wrap;
        word-wrap: break-word;
        overflow-wrap: break-word
    }
    .common {
        width: 500px;
        min-height: 50px;
        font-family: Arial, sans-serif;
        font-size: 13px;
        overflow: hidden;
    }
    .lbr {
        line-height: 3px;
    }
    

    HTML

    <textarea id="comments" placeholder="Type many lines of texts in here and you will see magic stuff" class="common"></textarea>
    

    脚本

    let txt = $('#comments'),
        txt.addClass('txtstuff');
    let hiddenDiv = $(document.createElement('div')),
        hiddenDiv.addClass('hiddendiv common');
    let content = null;
    
    $('body').append(hiddenDiv);
    
    txt.on('keyup', function () {
        content = $(this).val();
        content = content.replace(/\n/g, '<br>');
        hiddenDiv.html(content + '<br class="lbr">');
        $(this).css('height', hiddenDiv.height());
    });
    

    FIDDLE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-12-11
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多