您的位置:首页 > 其它

textarea高度自适应,随文字增加自动撑开

2017-12-28 19:19 656 查看
需求: 随文字增多,将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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  textarea 自适应 高度