【问题标题】:Change height of textarea based on number of lines of text in javascript [duplicate]根据javascript中的文本行数更改textarea的高度[重复]
【发布时间】:2011-05-29 19:43:46
【问题描述】:

可能重复:
Autosizing textarea using prototype

如何根据用户输入的文本行数更改文本区域的高度?

对于下面的示例,如果用户将 textarea 中的文本更改为多行文本,则 textarea 会在其自身上放置一个滚动条,而不是更改其高度以适应行数。

<textarea>
This is the default text that will be displayed in the browser. When you change this text and add more lines to it the browser will not change the height of the textarea that this text is in rather it will add a scroll bar, which is not what I want.
<textarea>

【问题讨论】:

  • @FelixKling 仅当我们假设 OP 使用原型时,他从未提及。

标签: javascript resize textarea height row-height


【解决方案1】:
<textarea onkeyup="autoSize(this);"></textarea>

function autoSize(ele)
{
   ele.style.height = 'auto';
   var newHeight = (ele.scrollHeight > 32 ? ele.scrollHeight : 32);
   ele.style.height = newHeight.toString() + 'px';
}

调整“32”以匹配行高留作练习。

【讨论】:

  • 它不起作用:jsfiddle.net/MYrG2
  • JSFiddle 问题,而不是脚本问题。来自 Chrome:“不安全的 JavaScript 尝试从 URL fiddle.jshell.net/MYrG2/show 的框架访问具有 URL jsfiddle.net/MYrG2 的框架。域、协议和端口必须匹配。”跨站脚本错误,多古怪。
  • 糟糕,一个小补充:为了解决 Webkit 上的问题,应该在 textarea 样式中添加“overflow-y: hidden”。
  • 对贬损性评论投反对票。
  • 不要忘记调整填充。 scrollHeight 似乎包括顶部和底部填充。
猜你喜欢
  • 2021-03-05
  • 2014-04-20
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
  • 2012-04-08
相关资源
最近更新 更多