这个问题可能不在此网站上,但我不知道在哪里寻找这样的东西,所以我很抱歉。
所以我正在使用Google表单,以一个长答案的问题制作虚拟测试表格,我试图弄清楚文本区域是如何使用其内容扩展的,但调整大小是禁用的。
当我增加文本量时,超过300个Lorem ipsum coracters,文本的最后一行和textarea
的底部之间存在差距,将文本粘贴了几次,只会增加空间的数量。我的猜测是,与textarea
框中写的字符相比,Google使用线上拟合的平均搬运量计算文本的高度。
所以我想知道是否有一种方法可以更准确地检测textarea
中的线量并像在Google表单上一样调整其高度(但也许更好?)
我在想:
- 也许对每个字母的单个宽度和然后计算下一个字母是否适合行。?
- 也许隐藏在视图div的情况下,宽度相同和相同文本样式并将文本快速复制到DIV,然后复制Div的偏移高度到文本方面?
- 也许我错过了你们可能知道的东西?
让我知道你的苦苦挣扎!
这可以使用jQuery来解决这个问题,如果有人正在寻找可靠的解决方案,该解决方案可以超过英里字符并在不到5秒内处理高度!
$('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>