js实现textarea高度根据内容自适应

js实现textarea高度跟随着内容变化。

实现代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<textarea rows="1" id="test" >六月初博客站</textarea>
<script>
function makeExpandingArea(el) {
var el = document.getElementById(el);
var setStyle = function(el) {
el.style.height = 'auto';
el.style.height = el.scrollHeight + 'px';
console.log(el.scrollHeight);
}
var delayedResize = function(el) {
window.setTimeout(function() {
setStyle(el)
},
0);
}
if (el.addEventListener) {
el.addEventListener('input',function() {
setStyle(el)
},false);
setStyle(el)
} else if (el.attachEvent) {
el.attachEvent('onpropertychange',function() {
setStyle(el)
});
setStyle(el)
}
if (window.VBArray && window.addEventListener) { //IE9
el.attachEvent("onkeydown",function() {
var key = window.event.keyCode;
if (key == 8 || key == 46) delayedResize(el);

});
el.attachEvent("oncut",function() {
delayedResize(el);
}); //处理粘贴
}
}
makeExpandingArea('test');
</script>
</body>
</html>

实现原理:监听输入框的变换来控制高度!获取滚动隐藏的高度!

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!