需求: 随文字增多,将textarea自动撑开。
解决思路: pre标签能保持文本的格式,将textarea的文本内容和样式严格复制一份给pre标签,pre的高度值就为我们所需的textarea的高度值。然后将pre隐藏。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
#fit1{
width: 674px;
margin: 0 0 30px 0;
padding: 10px 10px 20px;
border: 1px solid #e6e6e6;
min-height: 88px;
resize: none;
line-height: 24px;
border-radius: 3px;
font-size: 14px;
font-family: '微软雅黑', Helvetica, sans-serif;
overflow: hidden;
word-wrap: break-word;
white-space: pre-wrap;
}
.hide{
visibility: hidden;
position: absolute;
z-index: -100;
}
#fit2{
width: 674px;
padding: 10px 10px 20px;
min-height: 88px;
resize: none;
border: 1px solid #e6e6e6;
line-height: 24px;
border-radius: 3px;
font-size: 14px;
font-family: '微软雅黑', Helvetica, sans-serif;
overflow: hidden;
word-wrap: break-word;
}
</style>
<body>
<div>
<pre id="fit1" class="hide"></pre>
<textarea id="fit2"></textarea>
</div>
<script>
//高度自适应
document.onkeydown = function () {
var textarea = document.getElementById('fit2')
var pre = document.getElementById('fit1');
pre.innerHTML = textarea.value;
var realHeight = pre.offsetHeight;//offsetHeight = height + padding + border
if(realHeight > 120) textarea.style.height = (realHeight + 24 -32) + 'px'; //加24为一行的高度,减32为padding和border
else textarea.style.height = realHeight - 32 + 'px';
}
</script>
</body>
</html>
方法二:
<!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;}
.t pre{width:20em;}
pre{
white-space:pre-wrap;
word-wrap:break-word;
}
#divhidden{
visibility:hidden;
}
</style>
</head>
<body>
<textarea id="textareas" class="t" onkeyup="autoTextarea()"> </textarea>
<div class="t" id="divhidden"></div>
<script language="javascript">
function autoTextarea(){
var divhidden = document.getElementById("divhidden");
var textareas = document.getElementById("textareas");
var val = textareas.value;
divhidden.innerHTML ="<pre>" +val+" "+"</pre>";
textareas.style.height = (divhidden.offsetHeight-2) + "px";
if(val == ""){
textareas.value = " ";
}
}
</script>
</body>
</html>
不知道这个作者是谁了,sorry~
感谢分享https://blog.csdn.net/ls32140/article/details/78925452