在实现textarea根据内容的增多实现高度自适应,且无滚动条的效果,方法有2种。
第一种方法:通过事件onkeyup来实现这样的效果
备注:onkeyup事件发生阶段
1、onkeyup事件会在键盘按键被松开时发生;
2、与onkeyup事件相关的事件发生次序:
1)onkeydown----------键盘按下------------------------------------------------所有浏览器都支持
2)onkeypress---------键盘按键被按下并释放一个键时发生----------不是适用于所有按键(如: ALT, CTRL, SHIFT, ESC)
3)onkeyup ----------键盘被松开-----------------------------------------------都支持
代码如下:
<p>方法一:onkeyup事件</p>
<textarea id="text-adaption" class="text-adaption" rows="1"></textarea>
<script>
// 法一
function $(id) {
return document.getElementById(id);
}
$("text-adaption").onkeyup = function() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + "px";
}
</script>
效果图:
高度会随着内容的增加而增加,但是每次高度的增加都会带来整体高度的轻微颤动,视觉效果不是很好。
第二种方法:通过oninput事件实现效果,支持冒泡
代码如下:
<p>方法二:oninput事件</p>
<textarea id="testHeight" oninput="autoHeight()"></textarea>
<script>
// 法二
function autoHeight(){
var x = document.getElementById("testHeight");
x.style.height = 'auto';
x.style.height = x.scrollHeight + "px";
}
</script>
效果图:
实现了高度随内容的增高而增高,且在高度增高的过程中,整体自然增高,无抖动现象出现,视觉效果完美。
方法一与方法二的样式如下:
<style type="text/css">
textarea {
resize: none;
}
.text-adaption {
width: 300px;
height: 34px;
overflow: hidden;
resize: none;
line-height: 24px;
font-size: 12px;
color: #666;
border: 1px solid #ccc;
outline: 0 none;
border-radius: 3px;
box-sizing: border-box;
}
</style>