动态扩展输入类型的高度" text"根据输入字段的字符数

时间:2014-05-22 22:30:53

标签: javascript jquery css forms

类似于下面的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;    
}

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

谢谢!

3 个答案:

答案 0 :(得分:10)

正如其他人解释的那样,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.

更新了演示:

这个新的更新演示修复了一些错误,它还支持Enter键,最大高度限制,首先不需要固定设置宽度(而是我们可以设置其最小宽度)。它的功能更加全面。

Updated Demo

答案 1 :(得分:8)

<强>更新的[2]:

由于scrollHeight始终等于height,我们必须在scrollHeight之前将高度设置为&#39; 1&#39; ,然后当我们删除<textarea>自动调整字符

$('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/

<强>更新:

正如朋友所说,<input type="text"/>没有换行符。我建议使用<textarea>

$('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/

答案 2 :(得分:1)

不是我的,但是效果很好:

CSS

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

HTML

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

脚本

printf("\n Quais os valores da Matriz B? \n");
for (i = 0; i < n_linhas_B; i++)
{
   for (j = 0; j < n_colunas_B; j++)
   {
     printf("\n Elemento [%d][%d]", i, j);
     matriz_B[i][j] = ler_comp();
   }
}
printf("\n >");

FIDDLE