方法一、 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>枫芸志 » 文本框textarea高度自适应增长/伸缩</TITLE>
<style>
textarea { height:100px; 300px; }
</style>
</HEAD>
<BODY>
<!--以下代码中onpropertychange:IE支持;oninput:FireFox支持;为了兼容IE和FF,所以加上了这个两个;-->
<textarea id="txtContent" rows="1" onpropertychange="ResizeTextarea()" oninput="ResizeTextarea()" onkeyup="ResizeTextarea()">晴枫制作
http://witmax.cn</textarea>
<script type="text/javascript">
// 最小高度
var minHeight = 100;
// 最大高度,超过则出现滚动条
var maxHeight = 300;
function ResizeTextarea(){
var t = document.getElementById('txtContent');
h = t.scrollHeight;
h = h > minHeight ? h : minHeight;
h = h > maxHeight ? maxHeight : h;
t.style.height = h + "px";
}
</script>
</BODY>
</HTML>
方法二、
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<HTML>
<HEAD>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>枫芸志 » 文本框textarea高度自适应增长/伸缩</TITLE>
</HEAD>
<BODY>
<textarea id="txtContent" rows="5" cols="50" onkeyup="ResizeTextarea()" style="overflow-y:hidden;">Textarea高度随内容自适应地增长,无滚动条
晴枫制作
http://witmax.cn</textarea>
<script type="text/javascript">
// 最小高度
var minRows = 5;
// 最大高度,超过则出现滚动条
var maxRows = 12;
function ResizeTextarea(){
var t = document.getElementById('txtContent');
if (t.scrollTop == 0) t.scrollTop=1;
while (t.scrollTop == 0){
if (t.rows > minRows)
t.rows--;
else
break;
t.scrollTop = 1;
if (t.rows < maxRows)
t.style.overflowY = "hidden";
if (t.scrollTop > 0){
t.rows++;
break;
}
}
while(t.scrollTop > 0){
if (t.rows < maxRows){
t.rows++;
if (t.scrollTop == 0) t.scrollTop=1;
}
else{
t.style.overflowY = "auto";
break;
}
}
}
</script>
</BODY>
</HTML>