以下是相关代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>textarea设置高度自适应且可设置最大高度</title>
<style>
textarea {
width: 100%;
height: 38px; /*最初高度设置为38px;在输入时,会自动换行,高度自适应,直到最大高度*/
}
</style>
<script src="./jquery-2.1.4.min.js"></script>
</head>
<body>
<!-- 配置textarea高度自适应增长 到最大高度后 出现滑动条-->
<div style="width:300px;height:200px">
<textarea></textarea>
</div>
<!-- 验证chrome下clientHeight,offsetHeight, -->
<div id="test" style="height:40px;width:200px;border:2px solid #ddd;
margin:5px;padding:5px;overflow:auto;">
kkkkkkkkk
</div>
</body>
<script>
var setTextareaMH = function (max_height) {
$('textarea').each(function () {
this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;');
if (max_height != 0) {
this.setAttribute('style', 'max-height:' + max_height + 'px');
}
}).on('input', function () {
this.style.height = 'auto';
this.style.height = (this.scrollHeight) + 'px';
});
}
$(document).ready(function () {
// var textMaxH = '0'
var textMaxH = '350'; //设置最大高度为150
setTextareaMH(textMaxH) //当textMaxH设置为0时,则不对textarea设置最大高度
});
var obj = document.getElementById("test");
//内容超过容器时 chrome
alert("obj clientHeight: " + obj.clientHeight);//33 clientHeight = padding + height - scrollbar.width(17)
alert("obj offsetHeight: " + obj.offsetHeight);//chrome 54 offsetHeight = padding + border + height
alert("obj scrollHeight: " + obj.scrollHeight);//72 当内容未撑开容器时高度为盒子高度,当内容撑开出现滚动条时是元素内容实际高度
//内容未超过容器时三个高度为: 50 54 50
</script>
</html>