1. 程式人生 > >textarea的高度隨輸入文字的多少變化

textarea的高度隨輸入文字的多少變化

break innerhtml add order ace gin public htm java

建議采用方法2

<textarea name="textarea" id="textarea" style=‘overflow-y: hidden;height:20px‘ onpropertychange="this.style.height = this.scrollHeight + ‘px‘;" oninput="this.style.height = this.scrollHeight + ‘px‘;">我是內容</textarea>
<script>

document.getElementById("textarea").style.height = document.getElementById("textarea").scrollHeight + 10 + "px";

</script>

方法2

<!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>
<style type="text/css">
*{margin:0; padding:0;}
.t{width:20em; font-size:12px; font-family:Arial, "宋體", sans-serif; line-height:25px; border:1px solid #09F; }
.t pre{width:20em;font-family:Arial, "宋體", sans-serif; }
pre{
white-space:pre-wrap;
white-space:-moz-pre-wrap;
white-space:-pre-wrap;
white-space:-o-pre-wrap;
word-wrap:break-word;
}
.box{width:240px;margin:50px auto; padding:15px; background:#ccc; border:1px solid #bbb;}
</style>
</head>

<body>
<div class="box">
<textarea id="t" class="t" onkeyup="d()" style="height:25px; overflow:hidden"> </textarea>
</div>
<div class="t" id="d" style="visibility:hidden;"></div>
<script language="javascript">
function d(){
var d = document.getElementById("d");
var t = document.getElementById("t");
var val = t.value;
d.innerHTML ="<pre>" +val+" "+"</pre>";
t.style.height = (d.offsetHeight-2) + "px";
if(val == ""){
t.value = " ";
}
}
</script>
</body>
</html>

textarea的高度隨輸入文字的多少變化