您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

根据输入到字段中的字符数动态扩展输入类型“文本”的高度

根据输入到字段中的字符数动态扩展输入类型“文本”的高度

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

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

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

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

其他 2022/1/1 18:13:54 有621人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶