【问题标题】:How to adjust the size of a textarea automatically如何自动调整文本区域的大小
【发布时间】:2019-02-28 18:26:12
【问题描述】:

我的问题在标题中: 如何使用 React 根据文本自动调整文本区域的大小

我想用 Refs 动态调整我的 textarea 高度并将其传递给 state,但它不能正常工作。

我创建了一个代码框来帮助您了解我到底想要什么。

https://codesandbox.io/s/ol5277rr25

在我的示例中,我使用 Ref 获取 textarea 高度,并将其传递给 onChange 事件中的状态,但是对于键入的每个字母,高度都会增加,它无法正常工作..

另一种解决方案是在换行时将 textarea 拆分为数组,并且对于每个换行符,增加 textarea 的高度(1 个换行符 = 1 行)。 但我无法检测到 自动 换行符(当我按下 Enter 时换行符没问题)..如果你有想法?

我已经用过 react-autosize-textarea 但我更喜欢自己做 :)

【问题讨论】:

  • 这个怎么样——不要使用'height',使用'rows':rows={ this.state.rows} `codesandbox.io/s/ny87x6pzm
  • 不工作,对于每个键入的字母,行增加:/
  • 实际上,这个做得很好:codepen.io/Libor_G/pen/eyzwOx -- 我不在乎 textarea 的行高是硬编码的,但它工作得很好
  • 谢谢@Snowmonkey,它可以工作,但它不是最佳方法,因为如果我们更改 line-height 值,textarea 高度会增加得足够多。但就目前而言,这是我可以测试的所有方法中效果最好的方法..
  • 如果您更改 lineheight,可能值得考虑计算它,而不是对其进行硬编码:stackoverflow.com/questions/4392868/…

标签: javascript css reactjs textarea


【解决方案1】:

那是因为你得到了Element.clientHeight,它是 CSS 高度 + 填充。我查看了你的沙箱,你有一个 4px 的填充。所以clientHeight每次增加4px。

解决这个问题并动态增加文本区域高度的方法是使用Element.scrollHeight 而不是clientHeight。就是这样!

编辑:还将填充设置为 0。

【讨论】:

  • 哦,对不起。忘了补充我把padding设置为0,这里是沙箱链接codesandbox.io/s/k386r4r6zv
  • 哦,谢谢它的工作!非常感谢,我将高度减去 8px,它与正常填充完美配合! :D
  • 当你删除文本时它不会缩小
【解决方案2】:

在设置新的height 值之前,您需要将height 设置为auto

var autosize = document.getElementsByClassName('autosize')[0];

addEvent(autosize, ['change', 'cut', 'paste', 'keydown' ], e => resize(autosize));

function addEvent(el, types, fn) {
  if (typeof types === 'string') types = [ types ];
  types.forEach(type => el.addEventListener(type, fn));
}

function resize(ara) {
  ara.style.height = 'auto'; /* Always set to auto before resizing... */
  ara.style.height = ara.scrollHeight + 'px';
}
.container {
  width: 80%;
  margin: 0 auto;
}
.autosize {
  width: 100%;
  height : auto;
}
<div class="container">
  <textarea class="autosize"></textarea>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2019-08-22
    • 1970-01-01
    • 2013-05-16
    • 2010-09-05
    • 1970-01-01
    相关资源
    最近更新 更多