- <!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>
- 方法二:
- <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>
- 方法三:
- <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>
- //该片段来自于http://www.codesnippet.cn/detail/180720134670.html
来源: http://www.codesnippet.cn/detail/180720134670.html