我有一个
textarea
,其修复 height
为 70px
。当我多次按 Enter 键换行时,我想让 height
的 textarea
增长。此时,在第 6 行之后会出现一个滚动条。这是有道理的,因为修复了 height
的 70px
。但有办法解决这个问题吗?
textarea {
min-height: 70px;
}
<textarea>Hello World! Click "enter" for more lines...</textarea>
你可以用一个简单的 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>
如果您只想使用
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>