textarea的高度随输入文字的多少变化

建议采用方法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>

posted @ 2017-05-04 17:11  扯线木偶1992  阅读(1922)  评论(1编辑  收藏  举报