栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

正如其他人解释的那样,

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 hiddenvar 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;}

更新的演示:

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442497.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号