【问题标题】:Make textarea with setted height grow when new line is added添加新行时使设置高度的文本区域增长
【发布时间】:2018-06-21 02:11:06
【问题描述】:

我有一个textarea,其中修复了height70px。当我多次按 Enter 换行时,我想让 heighttextarea 增长。目前,在第 6 行之后出现一个滚动条。这是有道理的,因为修复了height70px。但是有没有办法解决这个问题?

textarea {
  min-height: 70px;
}
<textarea>Hello World! Click "enter" for more lines...</textarea>

【问题讨论】:

  • 最小高度而不是高度?
  • @LelioFaieta 忘记写了,我试过最小高度,但没有用(见更新的 sn-p)。
  • 我认为您将需要 javascript 并控制内容的长度/输入量。

标签: javascript html css height textarea


【解决方案1】:

你可以用一个简单的javascript函数来处理这个,看看sn-p:

var textarea = document.getElementById('txtArea');

textarea.addEventListener('keydown', autosize);
             
function autosize(){
  var el = this;  
    setTimeout(function(){
      el.style.cssText = 'height:auto; padding:0';
      el.style.cssText = 'height:' + el.scrollHeight + 'px';
    },0);
  
}
textarea {
  min-height: 70px;
  overflow: hidden;
}
<textarea id="txtArea">Hello World! Click "enter" for more lines </textarea>

另外,如果你愿意,你可以添加一个最大高度,这里是 sn-p:

var textarea = document.getElementById('txtArea');

textarea.addEventListener('keydown', autosize);
             
function autosize(){
  var el = this;
  el.style.cssText = 'overflow: hidden !important';
  
  if (el.scrollHeight > 120){
      el.style.cssText = 'overflow: scroll !important';
      el.style.cssText = 'height: 120px';
      textarea.removeEventListener('keydown', autosize);
  }else{
    setTimeout(function(){
      el.style.cssText = 'height:auto; padding:0';
      el.style.cssText = 'height:' + el.scrollHeight + 'px';
    },0);
  }
}
textarea {
  min-height: 70px;
}
<textarea id="txtArea">Hello World! Click "enter" for more lines </textarea>

【讨论】:

  • 这似乎是解决 textarea 问题的最佳方法。我用纯 css 但没有 textarea 做了一个例子:codepen.io/STWebtastic/pen/EoLJKz 只要使用 contenteditable 元素,它也可以工作。注意:如果您采用此解决方案,则不能像使用 textareas 那样设置属性resize。您将不得不为这样的解决方案编写 JS。谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-09-06
  • 2014-12-14
  • 1970-01-01
  • 2012-06-29
  • 2011-05-11
  • 1970-01-01
  • 2021-12-10
  • 2018-07-11
相关资源
最近更新 更多