效果:
原理:
監(jiān)聽 textarea 的 input 事件的 scrollHeight 變化(scrollHeight 元素內(nèi)容高度),賦值給 height。文章來源:http://www.zghlxwxcb.cn/news/detail-780675.html
再給 textarea 設(shè)置最大最小高度,padding 為 0(它自身的),保證上下限。文章來源地址http://www.zghlxwxcb.cn/news/detail-780675.html
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
margin: 0;
}
.wrapper {
height: 100vh;
display: flex;
flex-direction: column;
color: white;
}
nav {
height: 60px;
background-color: blue;
position: fixed;
width: 100%;
}
main {
margin-top: 60px;
background-color: pink;
height: 100%;
flex: 1;
}
footer {
background-color: red;
width: 100%;
display: flex;
}
textarea {
min-height: 50px;
max-height: 300px;
padding: 0;
width: 100%;
}
</style>
</head>
<body>
<div class="wrapper">
<nav>nav</nav>
<main>main</main>
<footer>
<textarea></textarea>
</footer>
</div>
<script>
var textarea = document.querySelector("textarea");
textarea.addEventListener("input", (e) => {
textarea.style.height = 50 + "px"; // 刪除文本內(nèi)容,調(diào)整高度
textarea.style.height = e.target.scrollHeight + "px";
});
</script>
</body>
</html>
到了這里,關(guān)于textarea 內(nèi)容自適應(yīng),高度向上擴展的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!