还有另外一个关于这个问题,我试过了.但是有一个问题:textarea如果删除内容,则不会缩小.我找不到任何方法将它缩小到正确的大小 - clientHeight值返回为完整的大小,而textarea不是其内容.
该页面的代码如下:
function FitToContent(id, maxHeight)
{
var text = id && id.style ? id : document.getElementById(id);
if ( !text )
return;
var adjustedHeight = text.clientHeight;
if ( !maxHeight || maxHeight > adjustedHeight )
{
adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
if ( maxHeight )
adjustedHeight = Math.min(maxHeight, adjustedHeight);
if ( adjustedHeight > text.clientHeight )
text.style.height = adjustedHeight + "px";
}
}
window.onload = function() {
document.getElementById("ta").onkeyup = function() {
FitToContent( this, 500 ) …Run Code Online (Sandbox Code Playgroud) 我想要的是计算textarea中的行数,例如:
line 1
line 2
line 3
line 4
Run Code Online (Sandbox Code Playgroud)
最多可以计4行.基本上按一次输入会转移到下一行
以下代码无效:
var text = $("#myTextArea").val();
var lines = text.split("\r");
var count = lines.length;
console.log(count);
Run Code Online (Sandbox Code Playgroud)
无论有多少行,它总是给出'1'.
我有一个网络表单,我的客户希望用户能够打印出来。使用 CSS 进行一些样式设置时效果很好,但是,我有几个textaear字段。如果用户键入的内容超过 textarea 的高度,则打印时该类型将被截断。
我已经在打印样式表中尝试过textarea{height:100%;},textarea{height:auto;}但这些都不起作用。
有没有办法将 textarea 字段的大小调整为仅打印版本的文本大小?如果可能,我更喜欢 CSS 解决方案,我可以将其插入到我的打印样式表中。如果这是不可能的,javascript 解决方案将起作用。
截图对比:

注意:如果我不能只影响打印版本,我可以考虑使用 JS 在有人输入时自动调整 textarea 字段的大小。
javascript ×2
textarea ×2
css ×1
height ×1
html ×1
jquery ×1
print-style ×1
printing ×1
resize ×1