<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <body> <textarea onkeyup="MaxMe(this)" style="overflow: hidden"></textarea> <script type="text/javascript"> function MaxMe(o) { if (window.navigator.userAgent.indexOf("Firefox") > -1) { o.style.height = o.scrollTop + o.scrollHeight + "px"; } else { if (o.scrollTop > 0) o.style.height = o.scrollTop + o.scrollHeight + "px"; } } </script> <div id="debug"></div> </body> </html>
或者
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <title>Javascript 实现 Textarea 自动伸缩,兼容IE6、IE7、IE8、IE9、Firefox、Safari、Chome、Opera</title> </head> <body> <table> <tr valign="top"> <td><textarea id="textarea" style="overflow: hidden"></textarea></td> <td><textarea onpropertychange="MaxMe(this)" oninput="MaxMe(this)" ontextinput="MaxMe(this)" style="overflow: hidden"></textarea></td> </tr> </table> <script type="text/javascript"> function MaxMe(o) { if (window.navigator.userAgent.indexOf("Firefox") > -1) { o.style.height = o.scrollTop + o.scrollHeight + "px"; } else { if (o.scrollTop > 0) o.style.height = o.scrollTop + o.scrollHeight + "px"; } } function Init() { var textarea = document.getElementById("textarea"); if (textarea.addEventListener) { // 非Internet Explorer和Internet Explorer9之后的版本 textarea.addEventListener("input", OnTextInput, false); // Google Chrome 和 Safari textarea.addEventListener("textinput", OnTextInput, false); } if (textarea.attachEvent) { // Internet Explorer 和 Opera textarea.attachEvent("onpropertychange", OnTextInput); } } function OnTextInput(evt) { o = window.event ? window.event.srcElement : evt.target; if (window.navigator.userAgent.indexOf("Firefox") > -1) { o.style.height = o.scrollTop + o.scrollHeight + "px"; } else { if (o.scrollTop > 0) o.style.height = o.scrollTop + o.scrollHeight + "px"; } } window.onload = Init; </script> </body> </html>