添加新行时使具有设置高度的文本区域增长
Make textarea with setted height grow when new line is added
我有一个 textarea
,修正 height
为 70px
。当我多次按 enter 换行时,我想让 textarea
的 height
增长。此时,在第 6 行之后出现一个滚动条。这是有道理的,因为 70px
的修复 height
。但是有办法解决这个问题吗?
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>
我有一个 textarea
,修正 height
为 70px
。当我多次按 enter 换行时,我想让 textarea
的 height
增长。此时,在第 6 行之后出现一个滚动条。这是有道理的,因为 70px
的修复 height
。但是有办法解决这个问题吗?
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>