这个问题对于这个网站来说可能是错误的,但我不知道在哪里可以找到这样的东西,所以如果是的话,我很抱歉。
所以我在 Google 表单上制作了一个 dummy test form有一个很长的答案问题,我试图弄清楚文本区域如何随其内容扩展,但调整大小被禁用。
当我增加了超过 300 个 lorem ipsum 字符的文本量时,最后一行文本和 textarea
底部之间出现了间隙,粘贴文本几次只会增加空间量。我的猜测是,谷歌计算文本的近似高度时使用的是适合一行的平均字符数与写入 textarea
框中的字符数相比。
所以我想知道是否有一种方法可以更准确地检测 textarea
中的行数并像在 google 表单上那样调整它的高度(但也许更好?)
我在想:
- 也许可以精确测量每个字母的单独宽度和 然后计算下一个字母是否适合该行。?
- 也许有一个从 View 中隐藏的具有相同宽度和相同的div 文本样式并快速将文本复制到 div,然后复制 div 相对于 textarea 的偏移高度?
- 也许我漏掉了一些你们可能知道的东西?
告诉我你的强项!
最佳答案
如果有人正在寻找一种可靠的解决方案,可以在不到 5 秒的时间内处理一百万个字符并处理高度,那么这就是使用 jQuery 的技巧!
$('textarea').on('input propertychange paste', function() {
adjustTextareaHeight(this);
});
function adjustTextareaHeight( ta ) {
//Get the height of any padding and border that's computed by jQuery in .height
var padAndBordHeight = $(ta).outerHeight()-$(ta).height();
// because the scrollbar can cause calculation problems
$(ta).css( "overflow", "hidden" );
//Make the height of the <textarea> 0 to be able to get an "adjusted to content" read of the .scrollHeight
$(ta).height(0);
//Make the height of the <textarea> as tall as the .scrollHeight as it has wrapped the content of the text area
$(ta).height(ta.scrollHeight-(padAndBordHeight));
$(ta).parent().find("strong").toggleClass("visible",ta.scrollHeight>ta.offsetHeight);
//log the amount of lines in the console /!\ 20 is my line height /!\
/*console.log("There are "+Math.ceil($(ta).height()/20)+" lines in the current textarea");*//*my line heigh is 34*/
}
function textareaBlur(ta){
$(ta).height(20);
$(ta).parent().find("strong").toggleClass("visible",ta.scrollHeight>ta.offsetHeight);
}
$('textarea').each(function() {
adjustTextareaHeight(this);
})
/* textarea needs a line-height for the javascript to work */
#ta, #foo {
display:block;
width: 300px;
line-height: 20px;
height:20px;
resize:none;
overflow:hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="lines">...</div>
<textarea id="ta" rows="1" onfocus="adjustTextareaHeight(this);" onblur="textareaBlur(this)"></textarea>
<textarea id="foo" rows="1" onfocus="adjustTextareaHeight(this);" onblur="textareaBlur(this)"></textarea>
关于jquery - 如何使用 CSS 和 jQuery 将文本区域扩展到其内容并禁用手动调整大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564346/