添加新行时使设置高度的文本区域变大

问题描述 投票:0回答:2

我有一个

textarea
,其修复
height
70px
。当我多次按 Enter 键换行时,我想让
height
textarea
增长。此时,在第 6 行之后会出现一个滚动条。这是有道理的,因为修复了
height
70px
。但有办法解决这个问题吗?

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

javascript html css height textarea
2个回答
4
投票

你可以用一个简单的 JavaScript 函数来处理这个问题,看一下代码片段:

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>

另外,如果您愿意,您可以添加最大高度,以下是代码片段:

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>


0
投票

如果您只想使用

css
,您也可以像这样创建元素:

function contentTransfer(){
  document.getElementsByClassName("container")[0].innerHTML = document.getElementById("myTextArea").innerHTML;
}
.custom_textArea{
border: 1px solid lightGray;
padding: 7px;
border-radius: 7px;
outline: none;
}

.custom_textArea:focus{
border: 1px solid darkGray;
}
<p id="myTextArea" class="custom_textArea" contenteditable="true">my text</p>
<button onclick="contentTransfer()">get content</button>
<p class="container"></p>

© www.soinside.com 2019 - 2024. All rights reserved.