1 textarea id ="textarea" / textarea 2 script 3 function makeExpandingArea(el) { 4 var setStyle = function (el) { 5 el.style.height = ‘ auto ‘ ; 6 el.style.height = el.scrollHeight + ‘ px ‘ ; 7 // console.log(el.scrollHeight); 8 } 9
1 <textarea id="textarea"></textarea> 2 <script> 3 function makeExpandingArea(el) { 4 var setStyle = function(el) { 5 el.style.height = ‘auto‘; 6 el.style.height = el.scrollHeight + ‘px‘; 7 // console.log(el.scrollHeight); 8 } 9 var delayedResize = function(el) { 10 window.setTimeout(function() { 11 setStyle(el); 12 }, 13 0); 14 } 15 if (el.addEventListener) { 16 el.addEventListener(‘input‘,function() { 17 setStyle(el); 18 },false); 19 setStyle(el); 20 } else if (el.attachEvent) { 21 el.attachEvent(‘onpropertychange‘,function() { 22 setStyle(el); 23 }); 24 setStyle(el); 25 } 26 if (window.VBArray && window.addEventListener) { //IE9 27 el.attachEvent("onkeydown",function() { 28 var key = window.event.keyCode; 29 if (key == 8 || key == 46) delayedResize(el); 30 }); 31 el.attachEvent("oncut",function() { 32 delayedResize(el); 33 }); //处理粘贴 34 } 35 } 36 makeExpandingArea(textarea); 37 </script>
觉得不好看可以自己进行美化,修改样式就行了