定宽的textarea根据内容自动调整高度
程序员文章站
2022-06-10 11:45:42
...
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>固定textarea的宽度后,让textarea根据文本的长度自动调整它的高度。</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <br> 方法一: <textarea rows=1 cols=40 style='overflow:scroll;overflow-y:hidden;overflow-x:hidden' onfocus="window.activeobj=this;this.clock=setInterval(function(){activeobj.style.height=activeobj.scrollHeight+'px';},200);" onblur="clearInterval(this.clock);"></textarea> <br><br> 方法二: <script> var agt = navigator.userAgent.toLowerCase(); var is_op = (agt.indexOf("opera") != -1); var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op; function ResizeTextarea(a,row){ if(!a){return} if(!row) row=5; var b=a.value.split("\n"); var c=is_ie?1:0; c+=b.length; var d=a.cols; if(d<=20){d=40} for(var e=0;e<b.length;e++){ if(b[e].length>=d){ c+=Math.ceil(b[e].length/d) } } c=Math.max(c,row); if(c!=a.rows){ a.rows=c; } } </script> <textarea style="overflow: hidden; font-family: Verdana,Arial; font-style: normal; font-size: 13px; line-height: normal; " rows="4" cols="30" onfocus="javascript:ResizeTextarea(this,4);" onclick="javascript:ResizeTextarea(this,4);" onkeyup="javascript:ResizeTextarea(this,4);"></textarea> <br><br> 方法三: <script type="text/javascript"> //*2 var addHandler = window.addEventListener? function(elem,event,handler){elem.addEventListener(event,handler);}: function(elem,event,handler){elem.attachEvent("on"+event,handler);}; var $ = function(id){return document.getElementById(id);} function autoTextArea(elemid){ //½һtextareaû߶ if(!$("_textareacopy")){ var t = document.createElement("textarea"); t.id="_textareacopy"; t.style.position="absolute"; t.style.left="-9999px"; document.body.appendChild(t); } function change(){ $("_textareacopy").value= $(elemid).value; $(elemid).style.height= $("_textareacopy").scrollHeight+$("_textareacopy").style.height+"px"; } addHandler($("target"),"propertychange",change);//for IE addHandler($("target"),"input",change);// for !IE $(elemid).style.overflow="hidden";//һأġ $(elemid).style.resize="none";//ȥtextareaקŴ/С߶/ȹ } addHandler(window,"load",function(){ autoTextArea("target"); }); </script> <textarea id="target" rows="" cols=""></textarea> </body> </html>