这个是用jquery的例子:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script> <script type="text/javascript"> <!-- $(function(){ $("#ttt").bind("keydown keyup",function(){ $(this).autosize(); }).show().autosize(); }); $.fn.autosize = function(){ $(this).height('0px'); var setheight = $(this).get(0).scrollHeight; if($(this).attr("_height") != setheight) $(this).height(setheight+"px").attr("_height",setheight); else $(this).height($(this).attr("_height")+"px"); } --> </script> </head> <body> <textarea id="ttt" rows="1" cols="100" style="overflow:hidden;"></textarea> </body> </html>
下面这个没有用到jquery的:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"> <HTML> <HEAD> <TITLE> New Document </TITLE> <META NAME="Generator" CONTENT="EditPlus"> <META NAME="Author" CONTENT=""> <META NAME="Keywords" CONTENT=""> <META NAME="Description" CONTENT=""> </HEAD> <BODY> <textarea id="tValue" style="overflow-y:hidden; height:18px;" onpropertychange="this.style.height='0px';this.style.height=this.scrollHeight + 'px'" oninput="this.style.height='0px';this.style.height=this.scrollHeight + 'px'" ></textarea> </BODY> </HTML>
(YY一下在onpropertychange里不要使用this.style.height='0px';要不在IE下会有问题)。